你在哪里放置一个将在ListFragment上加载数据的AsyncTask?

时间:2013-02-13 13:07:04

标签: android xmlhttprequest

正如问题所述,我会在哪里放置希望将数据加载到ListFragment上的AsyncTask?

我的MainActivity有三个片段。一个是包含类别的ListFragment。中间是一个片段,其中包含通过从类别中选择检索的数据。最后一个是另一个ListFragment,它将显示用户选择的那些。

这三个片段中的每一个都有自己的xml文件和自己的.java文件。主活动cml文件是我通过片段标签定义三个片段的位置。当我没有将任何数据加载到第一个列表片段时,它工作得很好。但是,当我开始通过http请求从远程服务器加载数据时,它失败了。我正在使用AsyncTask来实现它。

这是java文件

MenuCategory.java

package com.thesis.menubook;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.TargetApi;
import android.app.ListFragment;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class MenuCategory extends ListFragment {
    JSONParser jsonParser = new JSONParser();
    ArrayList<HashMap<String, String>> categoryList;
    private ProgressDialog pDialog;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        // LOAD CATEGORY ONTO LIST
        new GetCategories().execute();

    }


    class GetCategories extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
             super.onPreExecute();
             pDialog = new ProgressDialog(getActivity().getApplicationContext());
             pDialog.setMessage("Loading Categories. Please wait...");
             pDialog.setIndeterminate(false);
             pDialog.setCancelable(false);
             pDialog.show();
        }

        /**
         * Getting product details in background thread
         * */
        protected String doInBackground(String... param) {
            Bundle b = getActivity().getIntent().getExtras();
            String ipaddress = b.getString("IPAddress");

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            Log.d("IP ADDRESS", ipaddress +" ");

            JSONObject json = jsonParser.makeHttpRequest("http://"+ipaddress+"/MenuBook/selectCategories.php", "GET", params);

            // Check your log cat for JSON reponse
            Log.d("All Categories: ", json.toString() + " ");

            try {
                // Checking for SUCCESS TAG
                int success = json.getInt("success");

                if (success == 1) {
                    // products found
                    // Getting Array of Products

                    JSONArray category_list = json.getJSONArray("category_list");

                    // looping through All Products
                    for (int j = 0; j < category_list.length(); j++) {
                        JSONObject c = category_list.getJSONObject(j);

                        // Storing each json item in variable
                        String category = c.getString("category");


                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        map.put("category", category);
                        int num = 1;
                        Log.d("category #"+num+"", category + "");
                        num++;
                        // adding HashList to ArrayList
                        if(categoryList.contains(map) != true)
                        {
                            categoryList.add(map);
                        }
                    }
                } 
            } catch (JSONException e) {
                e.printStackTrace();
            }

            ArrayAdapter<ArrayList<HashMap<String, String>>> arrayAdapter = new ArrayAdapter<ArrayList<HashMap<String, String>>>(getActivity().
                    getApplicationContext(), R.layout.activity_menu_category);
            arrayAdapter.add(categoryList);
            setListAdapter(arrayAdapter);

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        @Override
        protected void onPostExecute(String result) {
            pDialog.dismiss();

        }

    }

}

我这样做是否正确?或者我应该把它放在主要活动上吗?

1 个答案:

答案 0 :(得分:1)

因为您正在尝试从AsyncTask的doInBackground方法访问UI元素。您需要将onPostExecute中doInBackground的所有UI更新相关代码移动为:

class GetCategories extends AsyncTask<String, String, 
                     ArrayList<HashMap<String, String>>> {
 String ipaddress="";
        @Override
        protected void onPreExecute() {
          //your code here...
           Bundle b = getActivity().getIntent().getExtras();
           ipaddress = b.getString("IPAddress");
        }

        protected ArrayList<HashMap<String, String>> 
                           doInBackground(String... param) {


           // Your code here...

            return categoryList;
        }

        @Override
        protected void onPostExecute(String result) {

              // update ListView here 

             ArrayAdapter<ArrayList<HashMap<String, String>>> arrayAdapter = 
                  new ArrayAdapter<ArrayList<HashMap<String, String>>>
                                (getActivity().
                    getApplicationContext(), R.layout.activity_menu_category);
            arrayAdapter.add(result);
            Your_ListActivity.this.setListAdapter(arrayAdapter);
            pDialog.dismiss();

        }

    }
相关问题