通用图像加载器NullPointer

时间:2015-02-03 10:02:34

标签: android android-asynctask universal-image-loader

我正在使用Universal Image Loader Libray,但我在这一行return imageUrls.length;得到NullPointerError这是我的代码,我正在尝试使用AsyncTask获取图像。有人可以帮帮我吗?

public class ImageGridFragment extends AbsListViewBaseFragment {

    ProgressDialog mProgressDialog;

    String results;
    String jsonStr;

    JSONObject  jsonobjectdos;
    JSONArray  jsonarraydos;
    ListView listview;

    ArrayList<HashMap<String, String>> arraylist;

    String[] elementos_proximos;

    String mi_url;

    ImageLoader imageLoader;
    String[] imageUrls;

    public static final int INDEX = 1;



    DisplayImageOptions options;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);



        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.ic_stub)
                .showImageForEmptyUri(R.drawable.ic_empty)
                .showImageOnFail(R.drawable.ic_error)
                .cacheInMemory(true)
                .cacheOnDisk(true)
                .considerExifParams(true)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .build();
        new DownloadJSONdos().execute();
    }


    //MIO PARA COGER IMÁGENES DINÁMICAMENTE
    private class DownloadJSONdos extends AsyncTask<Void, Void, Void> {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                // Create a progressdialog
                mProgressDialog = new ProgressDialog(getActivity());
                // Set progressdialog title
                //mProgressDialog.setTitle("Android JSON Parse Tutorial");
                // Set progressdialog message
                mProgressDialog.setMessage("Actualizando...");
                mProgressDialog.setIndeterminate(false);
                // Show progressdialog
                mProgressDialog.show();
            }

            @Override
            protected Void doInBackground(Void... params) {
                // Create an array

                elementos_proximos =new String[500];
                // Retrieve JSON Objects from the given URL address
                jsonobjectdos = JSONfunctions
                        .getJSONfromURL("myurl");

                try {
                    // Locate the array name in JSON
                    if(jsonobjectdos == null) 
                        return null; 
                    jsonarraydos = jsonobjectdos.getJSONArray("results");

                    for (int i = 0; i < jsonarraydos.length(); i++) {

                        jsonobjectdos = jsonarraydos.getJSONObject(i);
                        // Retrive JSON Objects

                        mi_url=  jsonobjectdos.getString("url");

                        elementos_proximos[i]=mi_url;
                    }
                } catch (JSONException e) {
                    Log.e("Error", e.getMessage());
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void args) {



                 mProgressDialog.dismiss();
                 imageUrls= elementos_proximos;

            }
        }



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fr_image_grid, container, false);

        listView = (GridView) rootView.findViewById(R.id.grid);
        ((GridView) listView).setAdapter(new ImageAdapter());



        listView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                startImagePagerActivity(position);
            }
        });
        return rootView;
    }

    public class ImageAdapter extends BaseAdapter {

        private LayoutInflater inflater;

        ImageAdapter() {
            inflater = LayoutInflater.from(getActivity());
        }

        @Override
        public int getCount() {
            //return imageUrls.length;
            return imageUrls.length;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final ViewHolder holder;
            View view = convertView;


            if (view == null) {
                view = inflater.inflate(R.layout.item_grid_image, parent, false);
                holder = new ViewHolder();
                assert view != null;
                holder.imageView = (ImageView) view.findViewById(R.id.image);
                holder.progressBar = (ProgressBar) view.findViewById(R.id.progress);
                view.setTag(holder);
            } else {

                holder = (ViewHolder) view.getTag();
            }

            ImageLoader.getInstance()
                    .displayImage(imageUrls[position], holder.imageView, options, new SimpleImageLoadingListener() {
                        @Override
                        public void onLoadingStarted(String imageUri, View view) {
                            holder.progressBar.setProgress(0);
                            holder.progressBar.setVisibility(View.VISIBLE);
                        }

                        @Override
                        public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                            holder.progressBar.setVisibility(View.GONE);
                        }

                        @Override
                        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                            holder.progressBar.setVisibility(View.GONE);
                        }
                    }, new ImageLoadingProgressListener() {
                        @Override
                        public void onProgressUpdate(String imageUri, View view, int current, int total) {
                            holder.progressBar.setProgress(Math.round(100.0f * current / total));
                        }
                    });

            return view;
        }
    }

    static class ViewHolder {
        ImageView imageView;
        ProgressBar progressBar;
    }
}

这是我的日志猫

02-03 11:16:41.982: E/AndroidRuntime(24048): FATAL EXCEPTION: main
02-03 11:16:41.982: E/AndroidRuntime(24048): Process: com.nostra13.universalimageloader.sample, PID: 24048
02-03 11:16:41.982: E/AndroidRuntime(24048): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.nostra13.universalimageloader.sample/com.nostra13.universalimageloader.sample.activity.SimpleImageActivity}: java.lang.NullPointerException
02-03 11:16:41.982: E/AndroidRuntime(24048):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2212)
02-03 11:16:41.982: E/AndroidRuntime(24048):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2271)
02-03 11:16:41.982: E/AndroidRuntime(24048):    at android.app.ActivityThread.access$800(ActivityThread.java:144)
02-03 11:16:41.982: E/AndroidRuntime(24048):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
02-03 11:16:41.982: E/AndroidRuntime(24048):    at android.os.Handler.dispatchMessage(Handler.java:102)
02-03 11:16:41.982: E/AndroidRuntime(24048):    at android.os.Looper.loop(Looper.java:136)
02-03 11:16:41.982: E/AndroidRuntime(24048):    at android.app.ActivityThread.main(ActivityThread.java:5146)
02-03 11:16:41.982: E/AndroidRuntime(24048):    at java.lang.reflect.Method.invokeNative(Native Method)
02-03 11:16:41.982: E/AndroidRuntime(24048):    at java.lang.reflect.Method.invoke(Method.java:515)
02-03 11:16:41.982: E/AndroidRuntime(24048):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:796)
02-03 11:16:41.982: E/AndroidRuntime(24048):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612)
02-03 11:16:41.982: E/AndroidRuntime(24048):    at dalvik.system.NativeStart.main(Native Method)
02-03 11:16:41.982: E/AndroidRuntime(24048): Caused by: java.lang.NullPointerException
02-03 11:16:41.982: E/AndroidRuntime(24048):    at com.nostra13.universalimageloader.sample.fragment.ImageGridFragment$ImageAdapter.getCount(ImageGridFragment.java:190)
02-03 11:16:41.982: E/AndroidRuntime(24048):    at android.widget.GridView.setAdapter(GridView.java:186)
02-03 11:16:41.982: E/AndroidRuntime(24048):    at com.nostra13.universalimageloader.sample.fragment.ImageGridFragment.onCreateView(ImageGridFragment.java:166)
02-03 11:16:41.982: E/AndroidRuntime(24048):    at android.support.v4.app.Fragment.performCreateView(Fragment.java:1460)
02-03 11:16:41.982: E/AndroidRuntime(24048):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:911)
02-03 11:16:41.982: E/AndroidRuntime(24048):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1088)
02-03 11:16:41.982: E/AndroidRuntime(24048):    at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
02-03 11:16:41.982: E/AndroidRuntime(24048):    at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1444)
02-03 11:16:41.982: E/AndroidRuntime(24048):    at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:551)
02-03 11:16:41.982: E/AndroidRuntime(24048):    at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1171)
02-03 11:16:41.982: E/AndroidRuntime(24048):    at android.app.Activity.performStart(Activity.java:5241)
02-03 11:16:41.982: E/AndroidRuntime(24048):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2178)
02-03 11:16:41.982: E/AndroidRuntime(24048):    ... 11 more

2 个答案:

答案 0 :(得分:0)

((GridView) listView).setAdapter(new ImageAdapter());

在asyncTask的onPostExecute中调用它。基本上你是在创建imageUrls字符串数组之前制作适配器

答案 1 :(得分:0)

您的imageUrls正在AsyncTask的onPostExecute()中初始化;在后台线程完成任务执行之前,可能正在从主线程调用count()函数。