简体   繁体   English

AsyncTask不做inInBackground

[英]AsyncTask doesn't doInBackground

I'm trying to load a ListView using an HTTP request towards my own Apache server, which outputs JSON. 我正在尝试使用HTTP请求向我自己的Apache服务器加载ListView,该服务器输出JSON。 The issue is, my Android app's doInBackground method never procs when I insert breakpoints and try to debug, I don't think it even reaches my server. 问题是,当我插入断点并尝试调试时,我的Android应用程序的doInBackground方法永远不会触发,我什至认为它甚至不会到达我的服务器。 The application just runs without the ListView showing up. 该应用程序仅在不显示ListView的情况下运行。 (Yes, I am aware that I edited out my IP in RESTFunctions.java, my actual server IP is there in my code). (是的,我知道我在RESTFunctions.java中编辑了我的IP,我的代码中有我的实际服务器IP)。

MainActivity.java: 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 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: 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 (This one, I picked off the internet somewhere): 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: 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 (This is an extension of the BaseAdapter): MediathequeListAdapter(这是BaseAdapter的扩展):

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;
    }
}

Call execute() on your AsyncTask implementation object. AsyncTask实现对象上调用execute()

    task.execute();

For more info check the link 有关更多信息,请检查链接

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

doInBackGround will be called when you call execute() method using your AsyncTask instance. 当您使用AsyncTask实例调用execute()方法时,将调用doInBackGround。 So you could try this: 因此,您可以尝试以下操作:

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();

or 要么

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

Use onPreExecute and onPostExecute Methods along with doInBackground for AsyncTask onPreExecuteonPostExecute方法与doInBackground用于AsyncTask

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM