如何在Fragment中执行AsyncTask

时间:2014-07-10 16:31:36

标签: android android-fragments android-asynctask

我试图通过JSON从url获取数据 我有问题在Fragment中执行AsyncTask 在AsyncTask中如何解析JSON

有人可以帮助我......

这下面是我的代码:

HalamanUtama.Java

package com.example.kaerusshop;



import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * A simple {@link android.support.v4.app.Fragment} subclass.
 * 
 */
public class HalamanUtama extends android.app.Fragment {
    private JSONObject jobject;
    private String xresult="";
    private ProgressDialog pDialog;
    private String url="http://192.168.1.2/kaerusshop/get_products.php";
    ServiceHandler jParser = new ServiceHandler();
    private static final String TAG_PRODUCTS = "products";
    private static final String TAG_PID = "pid";
    private static final String TAG_NAME = "name";
    private static final String TAG_MERK = "merk";
    private static final String TAG_SUCCESS = "success";
    JSONArray products = null;
    // contacts JSONArray
    JSONArray contacts = null;

    ArrayList<HashMap<String, String>> productsList;

    TextView text;
    public HalamanUtama() {
        // Required empty public constructor
        //new LoadAllProducts().execute();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        View view=inflater.inflate(R.layout.fragment_halaman_utama, container,
                false);

        ImageView image = (ImageView) view.findViewById(R.id.banner);
        ImageLoaderConfiguration configuration=new ImageLoaderConfiguration.Builder(getActivity().getApplicationContext()).build();
        ImageLoader.getInstance().init(configuration);
        DisplayImageOptions options=new DisplayImageOptions.Builder().cacheOnDisc(true).build();
        ImageLoader loader=ImageLoader.getInstance();
        loader.displayImage("https://www.google.com/images/srpr/logo11w.png", image, options);

        GridView gridView = (GridView) view.findViewById(R.id.grid_view1);
        gridView.setAdapter(new ImageAdapter(getActivity().getApplicationContext()));

        gridView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {
                // TODO Auto-generated method stub
                // Sending image id to FullScreenActivity
                Intent i = new Intent(getActivity().getApplicationContext(), FullImage.class);
                // passing array index
                i.putExtra("id", arg2);
                startActivity(i);
            }
        });



        text=(TextView) view.findViewById(R.id.txtjson);
        productsList = new ArrayList<HashMap<String, String>>();

        // Loading products in Background Thread
        new LoadAllProducts().execute();
        return view;
    }



    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);
        new LoadAllProducts().execute();
    }



    class LoadAllProducts 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 products. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * getting All products from url
         * */
        protected String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url, "GET", params);

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

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

                if (success == 1) {
                    // products found
                    // Getting Array of Products
                    products = json.getJSONArray(TAG_PRODUCTS);

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

                        // Storing each json item in variable
                        String id = c.getString(TAG_PID);
                        String name = c.getString(TAG_NAME);

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

                        // adding each child node to HashMap key => value
                        map.put(TAG_PID, id);
                        map.put(TAG_NAME, name);

                        // adding HashList to ArrayList
                        productsList.add(map);
                    }
                } else {
                    // no products found
                    // Launch Add New product Activity
                    //Intent i = new Intent(getApplicationContext(),
                            //NewProductActivity.class);
                    // Closing all previous activities
                    //i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    //startActivity(i);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all products
            pDialog.dismiss();
            // updating UI from Background Thread
            getActivity().runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                    text.setText(productsList.get(0).get(TAG_NAME));
                }
            });

        }

    }

}

这是我的logcat

07-10 23:03:00.610: D/AbsListView(28132): Get MotionRecognitionManager
07-10 23:03:00.730: D/AbsListView(28132): Get MotionRecognitionManager
07-10 23:03:00.790: E/libEGL(28132): call to OpenGL ES API with no current context (logged once per thread)
07-10 23:03:00.820: D/ProgressBar(28132): setProgress = 0
07-10 23:03:00.820: D/ProgressBar(28132): setProgress = 0, fromUser = false
07-10 23:03:00.820: D/ProgressBar(28132): mProgress = 0mIndeterminate = false, mMin = 0, mMax = 10000
07-10 23:03:00.990: D/dalvikvm(28132): GC_CONCURRENT freed 199K, 10% free 9546K/10503K, paused 14ms+3ms, total 113ms
07-10 23:03:00.990: D/dalvikvm(28132): WAIT_FOR_CONCURRENT_GC blocked 74ms
07-10 23:03:01.030: I/dalvikvm-heap(28132): Grow heap (frag case) to 10.437MB for 408896-byte allocation
07-10 23:03:01.080: D/dalvikvm(28132): GC_FOR_ALLOC freed 21K, 10% free 9923K/10951K, paused 55ms, total 55ms
07-10 23:03:01.130: W/ResourceType(28132): Failure getting entry for 0x010802c8 (t=7 e=712) in package 0 (error -75)
07-10 23:03:01.330: D/AndroidRuntime(28132): Shutting down VM
07-10 23:03:01.330: W/dalvikvm(28132): threadid=1: thread exiting with uncaught exception (group=0x410d32a0)
07-10 23:03:01.400: E/AndroidRuntime(28132): FATAL EXCEPTION: main
07-10 23:03:01.400: E/AndroidRuntime(28132): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.kaerusshop/com.example.kaerusshop.MainActivity}: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
07-10 23:03:01.400: E/AndroidRuntime(28132):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2092)
07-10 23:03:01.400: E/AndroidRuntime(28132):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2117)
07-10 23:03:01.400: E/AndroidRuntime(28132):    at android.app.ActivityThread.access$700(ActivityThread.java:134)
07-10 23:03:01.400: E/AndroidRuntime(28132):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1218)
07-10 23:03:01.400: E/AndroidRuntime(28132):    at android.os.Handler.dispatchMessage(Handler.java:99)
07-10 23:03:01.400: E/AndroidRuntime(28132):    at android.os.Looper.loop(Looper.java:137)
07-10 23:03:01.400: E/AndroidRuntime(28132):    at android.app.ActivityThread.main(ActivityThread.java:4867)
07-10 23:03:01.400: E/AndroidRuntime(28132):    at java.lang.reflect.Method.invokeNative(Native Method)
07-10 23:03:01.400: E/AndroidRuntime(28132):    at java.lang.reflect.Method.invoke(Method.java:511)
07-10 23:03:01.400: E/AndroidRuntime(28132):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007)
07-10 23:03:01.400: E/AndroidRuntime(28132):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
07-10 23:03:01.400: E/AndroidRuntime(28132):    at dalvik.system.NativeStart.main(Native Method)
07-10 23:03:01.400: E/AndroidRuntime(28132): Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
07-10 23:03:01.400: E/AndroidRuntime(28132):    at android.view.ViewRootImpl.setView(ViewRootImpl.java:702)
07-10 23:03:01.400: E/AndroidRuntime(28132):    at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:326)
07-10 23:03:01.400: E/AndroidRuntime(28132):    at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:224)
07-10 23:03:01.400: E/AndroidRuntime(28132):    at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:149)
07-10 23:03:01.400: E/AndroidRuntime(28132):    at android.app.Dialog.show(Dialog.java:277)
07-10 23:03:01.400: E/AndroidRuntime(28132):    at com.example.kaerusshop.HalamanUtama$LoadAllProducts.onPreExecute(HalamanUtama.java:135)
07-10 23:03:01.400: E/AndroidRuntime(28132):    at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
07-10 23:03:01.400: E/AndroidRuntime(28132):    at android.os.AsyncTask.execute(AsyncTask.java:534)
07-10 23:03:01.400: E/AndroidRuntime(28132):    at com.example.kaerusshop.HalamanUtama.onActivityCreated(HalamanUtama.java:118)
07-10 23:03:01.400: E/AndroidRuntime(28132):    at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:848)
07-10 23:03:01.400: E/AndroidRuntime(28132):    at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1035)
07-10 23:03:01.400: E/AndroidRuntime(28132):    at android.app.BackStackRecord.run(BackStackRecord.java:635)
07-10 23:03:01.400: E/AndroidRuntime(28132):    at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1399)
07-10 23:03:01.400: E/AndroidRuntime(28132):    at android.app.Activity.performStart(Activity.java:5056)
07-10 23:03:01.400: E/AndroidRuntime(28132):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2065)
07-10 23:03:01.400: E/AndroidRuntime(28132):    ... 11 more
07-10 23:03:01.661: I/Process(28132): Sending signal. PID: 28132 SIG: 9
07-10 23:03:48.406: D/AbsListView(29564): Get MotionRecognitionManager
07-10 23:03:48.436: D/AbsListView(29564): Get MotionRecognitionManager
07-10 23:03:48.486: E/libEGL(29564): call to OpenGL ES API with no current context (logged once per thread)
07-10 23:03:48.536: D/dalvikvm(29564): GC_FOR_ALLOC freed 206K, 10% free 9484K/10439K, paused 41ms, total 41ms
07-10 23:03:48.536: I/dalvikvm-heap(29564): Grow heap (frag case) to 10.377MB for 408896-byte allocation
07-10 23:03:48.566: D/dalvikvm(29564): GC_FOR_ALLOC freed 3K, 10% free 9881K/10887K, paused 31ms, total 31ms
07-10 23:03:48.576: D/ProgressBar(29564): setProgress = 0
07-10 23:03:48.576: D/ProgressBar(29564): setProgress = 0, fromUser = false
07-10 23:03:48.576: D/ProgressBar(29564): mProgress = 0mIndeterminate = false, mMin = 0, mMax = 10000
07-10 23:03:48.636: W/ResourceType(29564): Failure getting entry for 0x010802c8 (t=7 e=712) in package 0 (error -75)
07-10 23:03:48.676: D/AndroidRuntime(29564): Shutting down VM
07-10 23:03:48.676: W/dalvikvm(29564): threadid=1: thread exiting with uncaught exception (group=0x410d32a0)
07-10 23:03:48.696: E/AndroidRuntime(29564): FATAL EXCEPTION: main
07-10 23:03:48.696: E/AndroidRuntime(29564): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.kaerusshop/com.example.kaerusshop.MainActivity}: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
07-10 23:03:48.696: E/AndroidRuntime(29564):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2092)
07-10 23:03:48.696: E/AndroidRuntime(29564):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2117)
07-10 23:03:48.696: E/AndroidRuntime(29564):    at android.app.ActivityThread.access$700(ActivityThread.java:134)
07-10 23:03:48.696: E/AndroidRuntime(29564):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1218)
07-10 23:03:48.696: E/AndroidRuntime(29564):    at android.os.Handler.dispatchMessage(Handler.java:99)
07-10 23:03:48.696: E/AndroidRuntime(29564):    at android.os.Looper.loop(Looper.java:137)
07-10 23:03:48.696: E/AndroidRuntime(29564):    at android.app.ActivityThread.main(ActivityThread.java:4867)
07-10 23:03:48.696: E/AndroidRuntime(29564):    at java.lang.reflect.Method.invokeNative(Native Method)
07-10 23:03:48.696: E/AndroidRuntime(29564):    at java.lang.reflect.Method.invoke(Method.java:511)
07-10 23:03:48.696: E/AndroidRuntime(29564):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007)
07-10 23:03:48.696: E/AndroidRuntime(29564):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
07-10 23:03:48.696: E/AndroidRuntime(29564):    at dalvik.system.NativeStart.main(Native Method)
07-10 23:03:48.696: E/AndroidRuntime(29564): Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
07-10 23:03:48.696: E/AndroidRuntime(29564):    at android.view.ViewRootImpl.setView(ViewRootImpl.java:702)
07-10 23:03:48.696: E/AndroidRuntime(29564):    at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:326)
07-10 23:03:48.696: E/AndroidRuntime(29564):    at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:224)
07-10 23:03:48.696: E/AndroidRuntime(29564):    at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:149)
07-10 23:03:48.696: E/AndroidRuntime(29564):    at android.app.Dialog.show(Dialog.java:277)
07-10 23:03:48.696: E/AndroidRuntime(29564):    at com.example.kaerusshop.HalamanUtama$LoadAllProducts.onPreExecute(HalamanUtama.java:135)
07-10 23:03:48.696: E/AndroidRuntime(29564):    at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
07-10 23:03:48.696: E/AndroidRuntime(29564):    at android.os.AsyncTask.execute(AsyncTask.java:534)
07-10 23:03:48.696: E/AndroidRuntime(29564):    at com.example.kaerusshop.HalamanUtama.onActivityCreated(HalamanUtama.java:118)
07-10 23:03:48.696: E/AndroidRuntime(29564):    at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:848)
07-10 23:03:48.696: E/AndroidRuntime(29564):    at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1035)
07-10 23:03:48.696: E/AndroidRuntime(29564):    at android.app.BackStackRecord.run(BackStackRecord.java:635)
07-10 23:03:48.696: E/AndroidRuntime(29564):    at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1399)
07-10 23:03:48.696: E/AndroidRuntime(29564):    at android.app.Activity.performStart(Activity.java:5056)
07-10 23:03:48.696: E/AndroidRuntime(29564):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2065)
07-10 23:03:48.696: E/AndroidRuntime(29564):    ... 11 more

先谢谢......

1 个答案:

答案 0 :(得分:3)

使用活动上下文。无需使用getApplicationContext()

 pDialog = new ProgressDialog(getActivity());

When to call activity context OR application context?