2013-07-04 30 views
0

我想加載一個ListView使用HTTP請求對我自己的Apache服務器,它輸出JSON。問題是,當我插入斷點並嘗試調試時,我的Android應用程序的doInBackground方法永遠不會生效,我認爲它甚至不會到達我的服務器。該應用程序只運行沒有ListView顯示。 (是的,我知道我在RESTFunctions.java中編輯了我的IP,我的實際服務器IP在我的代碼中)。AsyncTask不會在背景

MainActivity.java:

public class MainActivity extends Activity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     DownloadMediaList task = new DownloadMediaList (MainActivity.this,new TheInterface() { 
      @Override 
      public void theMethod(ArrayList<Media> result) { 
       ListView lv = (ListView) findViewById(R.id.media_list); 
       lv.setAdapter(new MediathequeListAdapter(MainActivity.this, result)); 
      } 
     }); 

    } 

    public interface TheInterface { 
     public void theMethod(ArrayList<Media> result); 

     } 

} 

Media.java

public class Media { 

    private String title; 
    private String cover; 
    private String year; 
    private String length; 
    private String description; 

    public Media(){ 

    } 

    public Media(String title, String cover, String description){ 
     this.title = title; 
     this.cover = cover; 
     this.description = description; 
    } 

    public String getTitle(){ 
     return title; 
    } 

    public String getCover(){ 
     return cover; 
    } 

    public String getYear(){ 
     return year; 
    } 

    public String getLength(){ 
     return length; 
    } 

    public String getDescription(){ 
     return description; 
    } 

    public void setTitle(String title){ 
     this.title = title; 
    } 

    public void setCover(String cover){ 
     this.cover = cover; 
    } 

    public void setYear(String year){ 
     this.year = year; 
    } 

    public void setLength(String length){ 
     this.length = length; 
    } 

    public void setDescription(String description){ 
     this.description = description; 
    } 

    @Override 
    public String toString(){ 
     return "[Titre=" + title + ", jaquette=" + cover + ", annee=" + year + ", duree=" + length + ", description=" + description + "]"; 
    } 
} 

DownloadMediaList.java:

public class DownloadMediaList extends AsyncTask<Void, Void, ArrayList<Media>> { 

    ListView listView = null; 
    Activity mainActivity = null; 

    Context mainContext = null; 
    TheInterface mlistener; 

    public DownloadMediaList(Context main,TheInterface listener){ 
     this.mainContext = main; 
     mlistener = listener; 
    } 

    // Operations that we do on a different thread. 
    @Override 
    protected ArrayList<Media> doInBackground(Void... params){ 
     // Set an ArrayList to store the medias. 
     ArrayList<Media> mediaList = new ArrayList<Media>(); 

     // Call the REST API and get the request info and media list in a JSONObject. 
     RESTFunctions restRequest = new RESTFunctions(); 
     JSONObject jsonMedia = restRequest.getMediaList(); 

     // Try catch to catch JSON exceptions. 
     try { 
      // Store the media list into a JSONArray. 
      JSONArray mediaArray = jsonMedia.getJSONArray("media"); 

      // Create an instance of media to store every single media later. 
      Media media = new Media(); 

      // Loop through the JSONArray and add each media to the ArrayList. 
      for (int i=0; i<mediaArray.length();i++){ 
       media = new Media(); 
       JSONObject singleMedia = mediaArray.getJSONObject(i); 
       media.setTitle(singleMedia.getString("titre")); 
       media.setYear(singleMedia.getString("annee")); 
       media.setLength(singleMedia.getString("duree")); 
       mediaList.add(media); 
      } 
     } catch (JSONException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

     // Return the ArrayList. 
     return mediaList; 
    } 

    // Operations we do on the User Interface. Synced with the User Interface. 
    @Override 
    protected void onPostExecute(ArrayList<Media> mediaList){ 
     if (mlistener != null) 
     { 
      mlistener.theMethod(mediaList); 
     } 
    } 
} 

JSONParser.java(這一項,我什麼地方剔去互聯網) :

public class JSONParser { 

    static InputStream is = null; 
    static JSONObject jObj = null; 
    static String json = ""; 

    // constructor 
    public JSONParser() { 

    } 

    public JSONObject getJSONFromUrl (String url, List<NameValuePair> params) { 

     // Making HTTP request 
     try { 
      // defaultHttpClient 
      DefaultHttpClient httpClient = new DefaultHttpClient(); 
      HttpPost httpPost = new HttpPost(url); 
      httpPost.setEntity(new UrlEncodedFormEntity(params)); 

      HttpResponse httpResponse = httpClient.execute(httpPost); 
      HttpEntity httpEntity = httpResponse.getEntity(); 
      is = httpEntity.getContent(); 

     } catch (UnsupportedEncodingException e) { 
      e.printStackTrace(); 
     } catch (ClientProtocolException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     try { 
      BufferedReader reader = new BufferedReader(new InputStreamReader(
        is, "iso-8859-1"), 8); 
      StringBuilder sb = new StringBuilder(); 
      String line = null; 
      while ((line = reader.readLine()) != null) { 
       sb.append(line + "n"); 
      } 
      is.close(); 
      json = sb.toString(); 
      Log.e("JSON", json); 
     } catch (Exception e) { 
      Log.e("Buffer Error", "Error converting result " + e.toString()); 
     } 

     // try parse the string to a JSON object 
     try { 
      jObj = new JSONObject(json);    
     } catch (JSONException e) { 
      Log.e("JSON Parser", "Error parsing data " + e.toString()); 
     } 

     // return JSON String 
     return jObj; 

    } 
} 

RESTFunctions.java:

public class RESTFunctions { 
    private JSONParser jsonParser; 

    private static String url = "http://*MY SERVER IP HERE*/mediatheque_api"; 

    public RESTFunctions() { 
     jsonParser = new JSONParser(); 
    } 

    // Gets a JSON Object containing the id, title, year, length, and cover of all albums. 
    public JSONObject getMediaList(){ 
     List<NameValuePair> params = new ArrayList<NameValuePair>(); 

     // We add the request name to get all medias from the API service 
     params.add(new BasicNameValuePair("req","listemedias")); 

     // We get the JSON Object from the API service 
     JSONObject json = jsonParser.getJSONFromUrl(url, params); 

     return json; 
    } 
} 

MediathequeListAdapter(這是BaseAdapter的擴展名):您的AsyncTask實施對象

public class MediathequeListAdapter extends BaseAdapter { 

    private ArrayList listData; 
    private LayoutInflater layoutInflater; 

    public MediathequeListAdapter(Context context, ArrayList listData){ 
     this.listData = listData; 
     layoutInflater = LayoutInflater.from(context); 
    } 

    @Override 
    public int getCount(){ 
     return listData.size(); 
    } 

    @Override 
    public Object getItem(int position){ 
     return listData.get(position); 
    } 

    @Override 
    public long getItemId(int position){ 
     return position; 
    } 

    public View getView(int position, View convertView, ViewGroup parent){ 
     ViewHolder holder; 
     if (convertView == null){ 
      convertView = layoutInflater.inflate(R.layout.mediatheque_listview, null); 
      holder = new ViewHolder(); 
      holder.title = (TextView) convertView.findViewById(R.id.title); 
      holder.year = (TextView) convertView.findViewById(R.id.year); 
      holder.length = (TextView) convertView.findViewById(R.id.length); 
      convertView.setTag(holder); 
     } else { 
      holder = (ViewHolder) convertView.getTag(); 
     } 

     Media media = (Media) listData.get(position); 
     holder.title.setText(media.getTitle()); 
     holder.year.setText(media.getYear()); 
     holder.length.setText(media.getLength()); 

     return convertView; 
    } 

    static class ViewHolder { 
     TextView title; 
     TextView year; 
     TextView length; 
    } 
} 
+1

你試圖調用task.execute(),以您的DownloadMediaList是否從onCreate()執行? – sandrstar

回答

3

呼叫​​。

task.execute(); 

欲瞭解更多信息檢查鏈接

http://developer.android.com/reference/android/os/AsyncTask.html

+0

沒有。我認爲這是task.start(),因爲沒有辦法,我只是放棄了它。現在,它的工作原理,我只是有POST問題的一些問題。如果可能的話,我希望得到一些幫助。 – Sefam

+1

@Sefam'execute'會調用asynctask。 – Raghunandan

+0

是的,它的確如此。我只是有一個額外的問題,我無法弄清楚發生了什麼事情。如果我自己發送一個請求到我的頁面,我實際上得到了我需要的JSON。我就此事開始了另一個問題http://stackoverflow.com/questions/17462571/httppost-not-sending-proper-values – Sefam

1

doInBackGround會使用您的AsyncTask實例調用,當你調用execute()方法。所以,你可以試試這個:

DownloadMediaList task = new DownloadMediaList (MainActivity.this,new TheInterface() { 
     @Override 
     public void theMethod(ArrayList<Media> result) { 
      ListView lv = (ListView) findViewById(R.id.media_list); 
      lv.setAdapter(new MediathequeListAdapter(MainActivity.this, result)); 
     } 
    }).execute(); 

task.execute(); //at some part appropriate in your code. 
0

使用onPreExecuteonPostExecute方法以及doInBackgroundAsyncTask

new AsyncTask<Void, Void, Boolean>() { 

      Exception error; 

      @Override 
      protected void onPreExecute() { 
       Toast.makeText(MainActivity.this, 
         "Start...", Toast.LENGTH_SHORT) 
         .show(); 

       setProgressBarIndeterminateVisibility(true); 
      } 

      @Override 
      protected Boolean doInBackground(Void... arg0) { 
       try { 
         Toast.makeText(MainActivity.this, 
         "Process in Background...", Toast.LENGTH_SHORT) 
         .show(); 
         return true; 
        } 
       catch (Exception e) 
        { 
        Log.e(TAG, "Error: " + e.getMessage(), error); 
        error = e; 

        return false; 
        } 


      } 

      @Override 
      protected void onPostExecute(Boolean result) { 
       setProgressBarIndeterminateVisibility(false); 

       if (result) { 
        Toast.makeText(MainActivity.this, "End....", 
          Toast.LENGTH_LONG).show(); 
       } else { 
        Toast.makeText(MainActivity.this, error.getMessage(), 
          Toast.LENGTH_LONG).show(); 
       } 
      } 

     }.execute();