在android中通过url加载图像

时间:2014-04-23 09:22:21

标签: android android-asynctask

Iam在后台通过图像解码从url加载Listview中的图像,但是出现以下错误。

        package com.abc;

        import java.io.InputStream;
        import java.net.URL;
        import java.sql.Array;
        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.R.integer;
        import android.app.ListActivity;
        import android.app.ProgressDialog;
        import android.content.Context;
        import android.content.Intent;
        import android.graphics.Bitmap;
        import android.graphics.BitmapFactory;
        import android.graphics.drawable.Drawable;
        import android.media.Image;
        import android.os.AsyncTask;
        import android.os.Bundle;
        import android.util.Log;
        import android.view.View;
        import android.widget.AdapterView;
        import android.widget.AdapterView.OnItemClickListener;
        import android.widget.GridView;
        import android.widget.ListAdapter;
        import android.widget.ListView;
        import android.widget.SimpleAdapter;
        import android.widget.TextView;

        public class FoodView extends ListActivity 
        {
            private ProgressDialog pDialog;
            private String[] mStrings;

            JSONParser jParser = new JSONParser();

            ArrayList<HashMap<String, String>> productsList;

            private static String url_all_products = "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;

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

        //      productsList = new ArrayList<HashMap<String, String>>();        // Hashmap for ListView
                new LoadAllProducts().execute();                                // Loading products in Background Thread by explicit function

                ListView listview = getListView();                                  // Get listview



                listview.setOnItemClickListener(new OnItemClickListener() {         // on seleting single product // launching Edit Product Screen
        @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
                    {
                        //getting values from selected ListItem
                        String pid = ((TextView) view.findViewById(R.id.pid)).getText().toString();
                        String pname = ((TextView) view.findViewById(R.id.name)).getText().toString();
                        String pimg = ((TextView) view.findViewById(R.id.img)).getText().toString();
                        String pdestination = ((TextView) view.findViewById(R.id.destination)).getText().toString();
                        String pprice = ((TextView) view.findViewById(R.id.price)).getText().toString();
                    }
                });

            }

        class LoadAllProducts extends AsyncTask<String, String, String>
        {       
            ListView listView;
            ArrayList<ItemList> listArray = new ArrayList<ItemList>();
            CustomListViewAdapter customGridAdapter;

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

                /**
                 * 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("Getting all the list : ", json.toString());

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

                        if (success == 1) 
                        {
                            products = json.getJSONArray(TAG_PRODUCTS);
                            for (int i = 0; i < products.length(); i++) 
                            {
                                JSONObject c = products.getJSONObject(i);
                                String id = c.getString(TAG_PID);
                                String name = c.getString(TAG_NAME);
                                String img = c.getString(TAG_IMAGE);
                                String destination = c.getString(TAG_DESTINATION);
                                String price = c.getString(TAG_PRICE);

                                mStrings[i] = img;
                                String urldisplay = mStrings[i];
                                Bitmap mIcon11 = null;
                                  try {
                                    InputStream in = new java.net.URL(urldisplay).openStream();
                                    mIcon11 = BitmapFactory.decodeStream(in);
                                  } catch (Exception e) {
                                      Log.e("Error", e.getMessage());
                                      e.printStackTrace();
                                  }
                               listArray.add(new ItemList(mIcon11,id,name,destination,price));

                               listView = (ListView) findViewById(R.id.list_item);
                               customGridAdapter = new CustomListViewAdapter(FoodView.this, R.layout.row_grid, listArray);
                               listView.setAdapter(customGridAdapter);

                            }
                        } 
                        else 
                        {

                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    return null;
                }



            }
        }

获得以下错误

04-23 05:15:15.839: E/AndroidRuntime(1398): FATAL EXCEPTION: AsyncTask #1
04-23 05:15:15.839: E/AndroidRuntime(1398): Process: com.ambrogroup, PID: 1398
04-23 05:15:15.839: E/AndroidRuntime(1398): java.lang.RuntimeException: An error occured while executing doInBackground()
04-23 05:15:15.839: E/AndroidRuntime(1398):     at android.os.AsyncTask$3.done(AsyncTask.java:300)
04-23 05:15:15.839: E/AndroidRuntime(1398):     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
04-23 05:15:15.839: E/AndroidRuntime(1398):     at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
04-23 05:15:15.839: E/AndroidRuntime(1398):     at java.util.concurrent.FutureTask.run(FutureTask.java:242)
04-23 05:15:15.839: E/AndroidRuntime(1398):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
04-23 05:15:15.839: E/AndroidRuntime(1398):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
04-23 05:15:15.839: E/AndroidRuntime(1398):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
04-23 05:15:15.839: E/AndroidRuntime(1398):     at java.lang.Thread.run(Thread.java:841)
04-23 05:15:15.839: E/AndroidRuntime(1398): Caused by: java.lang.NullPointerException
04-23 05:15:15.839: E/AndroidRuntime(1398):     at com.ambrogroup.FoodView$LoadAllProducts.doInBackground(FoodView.java:129)
04-23 05:15:15.839: E/AndroidRuntime(1398):     at com.ambrogroup.FoodView$LoadAllProducts.doInBackground(FoodView.java:1)
04-23 05:15:15.839: E/AndroidRuntime(1398):     at android.os.AsyncTask$2.call(AsyncTask.java:288)
04-23 05:15:15.839: E/AndroidRuntime(1398):     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
04-23 05:15:15.839: E/AndroidRuntime(1398):     ... 4 more
04-23 05:15:15.899: I/Choreographer(1398): Skipped 43 frames!  The application may be doing too much work on its main thread.
04-23 05:15:16.339: I/Choreographer(1398): Skipped 196 frames!  The application may be doing too much work on its main thread.
04-23 05:15:16.659: I/Choreographer(1398): Skipped 206 frames!  The application may be doing too much work on its main thread.
04-23 05:15:17.009: I/Choreographer(1398): Skipped 222 frames!  The application may be doing too much work on its main thread.
04-23 05:15:17.819: I/Choreographer(1398): Skipped 527 frames!  The application may be doing too much work on its main thread.
04-23 05:15:18.139: I/Choreographer(1398): Skipped 124 frames!  The application may be doing too much work on its main thread.
04-23 05:15:18.769: E/WindowManager(1398): android.view.WindowLeaked: Activity com.ambrogroup.FoodView has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{b50b0648 V.E..... R.....ID 0,0-304,96} that was originally added here
04-23 05:15:18.769: E/WindowManager(1398):  at android.view.ViewRootImpl.<init>(ViewRootImpl.java:348)
04-23 05:15:18.769: E/WindowManager(1398):  at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
04-23 05:15:18.769: E/WindowManager(1398):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
04-23 05:15:18.769: E/WindowManager(1398):  at android.app.Dialog.show(Dialog.java:286)
04-23 05:15:18.769: E/WindowManager(1398):  at com.ambrogroup.FoodView$LoadAllProducts.onPreExecute(FoodView.java:98)
04-23 05:15:18.769: E/WindowManager(1398):  at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
04-23 05:15:18.769: E/WindowManager(1398):  at android.os.AsyncTask.execute(AsyncTask.java:535)
04-23 05:15:18.769: E/WindowManager(1398):  at com.ambrogroup.FoodView.onCreate(FoodView.java:63)
04-23 05:15:18.769: E/WindowManager(1398):  at android.app.Activity.performCreate(Activity.java:5231)
04-23 05:15:18.769: E/WindowManager(1398):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-23 05:15:18.769: E/WindowManager(1398):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
04-23 05:15:18.769: E/WindowManager(1398):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
04-23 05:15:18.769: E/WindowManager(1398):  at android.app.ActivityThread.access$800(ActivityThread.java:135)
04-23 05:15:18.769: E/WindowManager(1398):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
04-23 05:15:18.769: E/WindowManager(1398):  at android.os.Handler.dispatchMessage(Handler.java:102)
04-23 05:15:18.769: E/WindowManager(1398):  at android.os.Looper.loop(Looper.java:136)
04-23 05:15:18.769: E/WindowManager(1398):  at android.app.ActivityThread.main(ActivityThread.java:5017)
04-23 05:15:18.769: E/WindowManager(1398):  at java.lang.reflect.Method.invokeNative(Native Method)
04-23 05:15:18.769: E/WindowManager(1398):  at java.lang.reflect.Method.invoke(Method.java:515)
04-23 05:15:18.769: E/WindowManager(1398):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-23 05:15:18.769: E/WindowManager(1398):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-23 05:15:18.769: E/WindowManager(1398):  at dalvik.system.NativeStart.main(Native Method)
04-23 05:15:18.769: I/Choreographer(1398): Skipped 96 frames!  The application may be doing too much work on its main thread.
04-23 05:15:18.849: I/Choreographer(1398): Skipped 46 frames!  The application may be doing too much work on its main thread.
04-23 05:15:20.819: I/Process(1398): Sending signal. PID: 1398 SIG: 9

1 个答案:

答案 0 :(得分:0)

按照原因:

java.lang.NullPointerException in 
04-23 05:15:15.839: E/AndroidRuntime(1398):     at com.ambrogroup.FoodView$LoadAllProducts.doInBackground(FoodView.java:129)

调试你的代码并尝试打印响应json,它可能是null,你试图访问它。

PS如果实际行号与您的代码段相同,我注意到

FoodView.java:129有空 你在哪里访问

mStrings[i] = img;

并且尚未初始化mStrings数组,需要添加行

String[] mStrings= new String[products.length()];
在为for循环之前

,然后将值赋给mStrings数组

欢呼声