在ListView的JSON执行中获得意外错误

时间:2014-04-25 10:21:48

标签: android android-asynctask

我想从网址中获取数据和图片,并希望解码并添加到列表视图中。但我发现了一个意外的例外。请解决问题。

public class FoodView extends ListActivity {

    private ProgressDialog pDialog;
    JSONParser jParser = new JSONParser();
    ArrayList<HashMap<String, String>> productsList;
    private String[] sImage;

    private static String url_for_list = "http://ambrogroup.com/app/index/file/food";
    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";
    private static final String TAG_IMAGE = "img";
    private static final String TAG_DESTINATION = "destination";
    private static final String TAG_PRICE = "price";

    JSONArray products = null;

    ListView list;
    LazyImageLoadAdapter adapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.food_view);

        new LoadAllProducts().execute();
        ListView lv = getListView();    

        lv.setOnItemClickListener(new OnItemClickListener() {       
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
            {
                                        /*  String pid = ((TextView) view.findViewById(R.id.pid)).getText().toString();
                                            String pname = ((TextView) view.findViewById(R.id.name)).getText().toString();
                                            toast(pid + pname);
                                            // Starting new intent
                                            Intent in = new Intent(getApplicationContext(),EditProductActivity.class);
                                            // sending pid to next activity
                                            in.putExtra(TAG_PID, pid);
                                            // starting new activity and expecting some response back
                                            startActivityForResult(in, 100);
                                        */
                                        }
                                    });
    }


    protected void onActivityResult(int requestCode, int resultCode, Intent data) 
    {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 100) 
        {
            Intent intent = getIntent();
            finish();
            startActivity(intent);
        }

    }


    class LoadAllProducts extends AsyncTask<String, String, String>
    {       
        @Override
        protected void onPreExecute() 
        {
            super.onPreExecute();
            pDialog = new ProgressDialog(FoodView.this);
            pDialog.setMessage("Loading list. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show(); 
        }


        protected String doInBackground(String... args) 
        {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            JSONObject json = jParser.makeHttpRequest(url_for_list, "GET", params);
            Log.d("Getting all the list : ", json.toString());
            try
            {
                int success = json.getInt(TAG_SUCCESS);     
                if(success==1)
                {
                    Log.d("Message : ","Im in if");
                    products = json.getJSONArray(TAG_PRODUCTS);
                    sImage = new String[products.length()];

                    for (int i = 0; i < products.length(); i++)
                    {
                        Log.d("Message : ","Im in If For");

                        JSONObject c = products.getJSONObject(i);
                        String id = c.getString(TAG_PID);
                        String name = c.getString(TAG_NAME);
                        String price = c.getString(TAG_PRICE);
                        String destination = c.getString(TAG_DESTINATION);
                        String imgname = c.getString(TAG_IMAGE);

                        sImage[i] = c.getString(TAG_IMAGE);

                        Log.d("Message : ",sImage[i]);

                        HashMap<String, String> map = new HashMap<String, String>();
                        map.put(TAG_PID, id);
                        map.put(TAG_NAME, name);
                        map.put(TAG_DESTINATION, destination);
                        map.put(TAG_PRICE, price);
                        map.put(TAG_IMAGE, imgname);
                        productsList.add(map);

                        Log.d("Message : ", "Adding in map");
                    }
                }
                else
                {

                }
            }catch(JSONException j)
            {
                j.printStackTrace();
            }
            return null;
        }

        protected void postExecute()
        {
            pDialog.dismiss();
            runOnUiThread(new Runnable() 
            {
                public void run() 
                {
                    Log.d("Message : ", "Im in post Execute");
                    list=(ListView)findViewById(R.id.list1);    
                    adapter=new LazyImageLoadAdapter(FoodView.this, sImage,productsList);
                    list.setAdapter(adapter);
                }
            });
        }
    }


    @Override
    public void onDestroy()
    {
        list.setAdapter(null);
        super.onDestroy();
    }

    public OnClickListener listener=new OnClickListener()
    {
        @Override
        public void onClick(View arg0) 
        {
            adapter.imageLoader.clearCache();
            adapter.notifyDataSetChanged();
        }
    };


    public void onItemClick(int mPosition)
    {
        String tempValues = sImage[mPosition];
        Toast.makeText(FoodView.this,"Image URL : "+tempValues, Toast.LENGTH_LONG).show();
    }

}

Logcat错误

04-25 06:14:29.418: D/Message :(3010): Im in if
04-25 06:14:29.428: D/Message :(3010): Im in If For
04-25 06:14:29.428: D/Message :(3010): http://ambrogroup.com/assets/brands/foods/comingsoon.png
04-25 06:14:29.428: W/dalvikvm(3010): threadid=11: thread exiting with uncaught exception (group=0xb4a26ba8)
04-25 06:14:29.468: I/Choreographer(3010): Skipped 38 frames!  The application may be doing too much work on its main thread.
04-25 06:14:29.818: I/Choreographer(3010): Skipped 30 frames!  The application may be doing too much work on its main thread.
04-25 06:14:30.168: E/AndroidRuntime(3010): FATAL EXCEPTION: AsyncTask #1
04-25 06:14:30.168: E/AndroidRuntime(3010): Process: com.ambrogroup, PID: 3010
04-25 06:14:30.168: E/AndroidRuntime(3010): java.lang.RuntimeException: An error occured while executing doInBackground()
04-25 06:14:30.168: E/AndroidRuntime(3010):     at android.os.AsyncTask$3.done(AsyncTask.java:300)
04-25 06:14:30.168: E/AndroidRuntime(3010):     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
04-25 06:14:30.168: E/AndroidRuntime(3010):     at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
04-25 06:14:30.168: E/AndroidRuntime(3010):     at java.util.concurrent.FutureTask.run(FutureTask.java:242)
04-25 06:14:30.168: E/AndroidRuntime(3010):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
04-25 06:14:30.168: E/AndroidRuntime(3010):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
04-25 06:14:30.168: E/AndroidRuntime(3010):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
04-25 06:14:30.168: E/AndroidRuntime(3010):     at java.lang.Thread.run(Thread.java:841)
04-25 06:14:30.168: E/AndroidRuntime(3010): Caused by: java.lang.NullPointerException
04-25 06:14:30.168: E/AndroidRuntime(3010):     at com.ambrogroup.FoodView$LoadAllProducts.doInBackground(FoodView.java:138)
04-25 06:14:30.168: E/AndroidRuntime(3010):     at com.ambrogroup.FoodView$LoadAllProducts.doInBackground(FoodView.java:1)
04-25 06:14:30.168: E/AndroidRuntime(3010):     at android.os.AsyncTask$2.call(AsyncTask.java:288)
04-25 06:14:30.168: E/AndroidRuntime(3010):     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
04-25 06:14:30.168: E/AndroidRuntime(3010):     ... 4 more

以下是XML代码food_view.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
    <!-- Main ListView
         Always give id value as list(@android:id/list)
    -->
    <ListView
        android:id="@+id/list1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/background"
        />

    <ListView android:id="@id/android:list"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:drawSelectorOnTop="false"
            android:visibility="gone" />


</LinearLayout>

1 个答案:

答案 0 :(得分:0)

试试这个。

您尚未初始化 productsList ArrayList。在doInBackground

中对其进行初始化,如下所示
productsList = ArrayList<HashMap<String, String>>();