在AsyncTask类中设置适配器

时间:2015-11-22 09:52:00

标签: android android-asynctask

我有一个扩展片段和调用异步任务类的代码。但我不能设定采用者。我面对错误。我在下面添加片段和错误的代码: 设置适配器时,此错误在此行中:

                    lv.setAdapter(adapter);

这是一个扩展片段的完整代码:

    public class AllProductsActivity extends Fragment  {
    private RadioGroup radioGroup;
   private RadioButton radioSexButton;
   private Button btnDisplay;
   ListView  lv;
    private ProgressDialog pDialog;

    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();

    ArrayList<HashMap<String, String>> productsList;

    // url to get all products list
    private static String url_all_products = "http://192.168.1.108/android_connect/get_all_products.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_PRODUCTS = "products";
    private static final String TAG_PID = "pid";
    private static final String TAG_NAME = "name";

    // products JSONArray
    JSONArray products = null;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.all_products, container, false);


        productsList = new ArrayList<HashMap<String, String>>();
        LoadAllProducts downloadimage = new LoadAllProducts();
        lv = (ListView) rootView.findViewById(R.id.list);

         downloadimage.execute();
        return rootView;


        }

    }

    /**
     * Background Async Task to Load all product by making HTTP Request
     * */
    class LoadAllProducts extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(getActivity());
            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_all_products, "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 {

                }
            } 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 parsed JSON data into ListView
                     * */
                    MainCustomList adapter;
                   // lv = (ListView) getView().findViewById(R.id.list);

                    String[] test = new String[] { "1", "2", "3" };

                    adapter = new MainCustomList(getActivity(), test);


                   lv.setAdapter(adapter);

            //   }
           // });

        }







  }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
         lv = (ListView) view.findViewById(R.id.list);}


   }

错误:

11-22 14:14:25.080: D/AndroidRuntime(9863): Shutting down VM
11-22 14:14:25.090: W/dalvikvm(9863): threadid=1: thread exiting with uncaught exception (group=0x41cca8b0)
11-22 14:14:25.090: E/AndroidRuntime(9863): FATAL EXCEPTION: main
11-22 14:14:25.090: E/AndroidRuntime(9863): java.lang.NullPointerException
11-22 14:14:25.090: E/AndroidRuntime(9863):     at info.androidhive.tabsswipe.AllProductsActivity$LoadAllProducts.onPostExecute(AllProductsActivity.java:330)
11-22 14:14:25.090: E/AndroidRuntime(9863):     at info.androidhive.tabsswipe.AllProductsActivity$LoadAllProducts.onPostExecute(AllProductsActivity.java:1)
11-22 14:14:25.090: E/AndroidRuntime(9863):     at android.os.AsyncTask.finish(AsyncTask.java:631)
11-22 14:14:25.090: E/AndroidRuntime(9863):     at android.os.AsyncTask.access$600(AsyncTask.java:177)
11-22 14:14:25.090: E/AndroidRuntime(9863):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
11-22 14:14:25.090: E/AndroidRuntime(9863):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-22 14:14:25.090: E/AndroidRuntime(9863):     at android.os.Looper.loop(Looper.java:213)
11-22 14:14:25.090: E/AndroidRuntime(9863):     at android.app.ActivityThread.main(ActivityThread.java:5225)
11-22 14:14:25.090: E/AndroidRuntime(9863):     at java.lang.reflect.Method.invokeNative(Native Method)
11-22 14:14:25.090: E/AndroidRuntime(9863):     at java.lang.reflect.Method.invoke(Method.java:525)
11-22 14:14:25.090: E/AndroidRuntime(9863):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:741)
11-22 14:14:25.090: E/AndroidRuntime(9863):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
11-22 14:14:25.090: E/AndroidRuntime(9863):     at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:1)

下面:

lv.setAdapter(adapter);

导致NPE的行,因为lvnull

带有ListView

list位于Fragment而不是Fragment容器Activity

使用Fragment的getView方法代替getActivity从Fragment Layout访问ListView:

lv = (ListView) getView().findViewById(R.id.list);

或更好地使用Fragment的onViewCreatedonCreateView方法来初始化视图:

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
     lv = (ListView) view.findViewById(R.id.list);
}