-1

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

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

这三个片段中的每一个都有自己的 xml 文件和自己的 .java 文件。Main Activity 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();

        }

    }

}

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

4

1 回答 1

1

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

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

        }

    }
于 2013-02-13T13:20:30.820 回答