-1

質問が述べているように、ListFragment にデータをロードする AsyncTask をどこに配置しますか?

私の MainActivity には 3 つのフラグメントがあります。1 つは、カテゴリを含む ListFragment です。中央のものは、カテゴリから選択して取得したデータを含むフラグメントです。そして最後のものは、ユーザーが選択したものを表示する別の ListFragment です。

3 つのフラグメントのそれぞれに、独自の xml ファイルと独自の .java ファイルがあります。メイン アクティビティの cml ファイルは、フラグメント タグを使用して 3 つのフラグメントを定義する場所です。最初のリストフラグメントにデータをロードしていない場合は、問題なく動作します。しかし、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要素にアクセスしようとしているcurrenltyのため。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();

        }

    }
于 2013-02-13T13:20:30.820 に答える