简体   繁体   English

适配器内ImageView上的NullPointerException

[英]NullPointerException on ImageView inside Adapter

I am using ViewPager to hold my Fragments. 我正在使用ViewPager来保存我的片段。 I have two Fragments with different Parse Queries. 我有两个具有不同解析查询的片段。 One of My Fragment has grid view layout. 我的片段之一具有网格视图布局。 I have created and Adapter for the GridView to load images. 我已经为GridView创建了一个Adapter来加载图像。

This is my fragment 这是我的片段

public class FeedsFragment extends Fragment {
    GridView gridview;
    List<ParseObject> ob;
    FeedsGridAdapter adapter;
    private List<ParseFeeds> phonearraylist = null;
    View rootView;

    public static final String TAG = FeedsFragment.class.getSimpleName();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.feeds_layout,
                container, false);
        new RemoteDataTask().execute();
        return rootView;
    }


    private class RemoteDataTask extends AsyncTask<Void,Void,Void> {

       @Override
       protected void onPreExecute() {
           super.onPreExecute();
       }

        @Override
        protected Void doInBackground(Void... params) {
            // Create the array
            phonearraylist = new ArrayList<ParseFeeds>();
            try {
                // Locate the class table named "SamsungPhones" in Parse.com
                ParseQuery<ParseObject> query = new ParseQuery<ParseObject>(
                        "AroundMe");
                // Locate the column named "position" in Parse.com and order list
                // by ascending
               // query.whereEqualTo(ParseConstants.KEY_RECIPIENT_IDS, ParseUser.getCurrentUser().getUsername());
                query.orderByAscending("createdAt");
                ob = query.find();
                for (ParseObject country : ob) {
                    ParseFile image = (ParseFile) country.get("videoThumbs");
                    ParseFeeds map = new ParseFeeds();
                    map.setPhone(image.getUrl());
                    phonearraylist.add(map);
                }
            } catch (ParseException e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            // Locate the gridview in gridview_main.xml
            gridview = (GridView) rootView.findViewById(R.id.gridview);
            // Pass the results into ListViewAdapter.java
            adapter = new FeedsGridAdapter(FeedsFragment.this.getActivity(),
                    phonearraylist);
            // Binds the Adapter to the ListView
            gridview.setAdapter(adapter);
        }
    }

}

The Adapter I created to load the images into 我创建的将图像加载到的适配器

    public static final String TAG = FeedsGridAdapter.class.getSimpleName();

    // Declare Variables
    Context context;
    LayoutInflater inflater;
    ImageLoader imageLoader;
    private List<ParseFeeds> phonearraylist = null;
    private ArrayList<ParseFeeds> arraylist;

    public FeedsGridAdapter(Context context, List<ParseFeeds> phonearraylist) {
        this.context = context;
        this.phonearraylist = phonearraylist;
        inflater = LayoutInflater.from(context);
        this.arraylist = new ArrayList<ParseFeeds>();
        this.arraylist.addAll(phonearraylist);
        imageLoader = new ImageLoader(context);
    }

    public class ViewHolder {
        ImageView phone;
    }

    @Override
    public int getCount() {
        return phonearraylist.size();
    }

    @Override
    public Object getItem(int position) {
        return phonearraylist.get(position);
    }

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

    public View getView(final int position, View view, ViewGroup parent) {
        final ViewHolder holder;
        if (view == null) {
            holder = new ViewHolder();
            view = inflater.inflate(R.layout.feeds_layout, null);
            // Locate the ImageView in gridview_item.xml
            holder.phone = (ImageView) view.findViewById(R.id.videoThumb);
            view.setTag(holder);
        } else {
            holder = (ViewHolder) view.getTag();
        }
        // Load image into GridView
        imageLoader.DisplayImage(phonearraylist.get(position).getPhone(),
                holder.phone);
        // Capture GridView item click
        view.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // Send single item click data to SingleItemView Class
                Intent intent = new Intent(context, SingleVideoView.class);
                // Pass all data phone
                intent.putExtra("phone", phonearraylist.get(position)
                        .getPhone());
                context.startActivity(intent);
            }
        });
        return view;
    }
}

Here its giving me NullPointerException on imageLoader.DisplayImage(phonearraylist.get(position).getPhone(), holder.phone); 这给了我ImageLoader.DisplayImage(phonearraylist.get(position).getPhone(),holder.phone)上的NullPointerException;

When I run the same code in another project with only one Fragment its working but when I use it in my current project with Two Fargments having different parse queries it gives me NullPointerException.Please help I wasted around 5 days on this to get it working tried everything possible at my end. 当我在另一个项目中运行相同的代码但仅工作一个Fragment时,但是当我在当前项目中使用两个Fargments具有不同的解析查询的代码时,则会显示NullPointerException。请帮助我浪费了大约5天的时间才能使其正常运行尽一切可能。

Here is my ImageLoader Class 这是我的ImageLoader类

    MemoryCache memoryCache = new MemoryCache();
    FileCache fileCache;
    private Map<ImageView, String> imageViews = Collections
            .synchronizedMap(new WeakHashMap<ImageView, String>());
    ExecutorService executorService;
    // Handler to display images in UI thread
    Handler handler = new Handler();

    public ImageLoader(Context context) {
        fileCache = new FileCache(context);
        executorService = Executors.newFixedThreadPool(5);
    }

   // int stub_id = ;

    public void DisplayImage(String url, ImageView imageView) {
        imageViews.put(imageView, url);
        Bitmap bitmap = memoryCache.get(url);
        if (bitmap != null)
            imageView.setImageBitmap(bitmap);
        else {
            queuePhoto(url, imageView);
            imageView.setImageResource(R.drawable.camera_iris);
        }
    }

    private void queuePhoto(String url, ImageView imageView) {
        PhotoToLoad p = new PhotoToLoad(url, imageView);
        executorService.submit(new PhotosLoader(p));
    }

    private Bitmap getBitmap(String url) {
        File f = fileCache.getFile(url);

        Bitmap b = decodeFile(f);
        if (b != null)
            return b;

        // Download Images from the Internet
        try {
            Bitmap bitmap = null;
            URL imageUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) imageUrl
                    .openConnection();
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setInstanceFollowRedirects(true);
            InputStream is = conn.getInputStream();
            OutputStream os = new FileOutputStream(f);
            Utils.CopyStream(is, os);
            os.close();
            conn.disconnect();
            bitmap = decodeFile(f);
            return bitmap;
        } catch (Throwable ex) {
            ex.printStackTrace();
            if (ex instanceof OutOfMemoryError)
                memoryCache.clear();
            return null;
        }
    }

    // Decodes image and scales it to reduce memory consumption
    private Bitmap decodeFile(File f) {
        try {
            // Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            FileInputStream stream1 = new FileInputStream(f);
            BitmapFactory.decodeStream(stream1, null, o);
            stream1.close();

            // Find the correct scale value. It should be the power of 2.
            final int REQUIRED_SIZE = 100;
            int width_tmp = o.outWidth, height_tmp = o.outHeight;
            int scale = 1;
            while (true) {
                if (width_tmp / 2 < REQUIRED_SIZE
                        || height_tmp / 2 < REQUIRED_SIZE)
                    break;
                width_tmp /= 2;
                height_tmp /= 2;
                scale *= 2;
            }

            // Decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            FileInputStream stream2 = new FileInputStream(f);
            Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2);
            stream2.close();
            return bitmap;
        } catch (FileNotFoundException e) {
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    // Task for the queue
    private class PhotoToLoad {
        public String url;
        public ImageView imageView;

        public PhotoToLoad(String u, ImageView i) {
            url = u;
            imageView = i;
        }
    }

    class PhotosLoader implements Runnable {
        PhotoToLoad photoToLoad;

        PhotosLoader(PhotoToLoad photoToLoad) {
            this.photoToLoad = photoToLoad;
        }

        @Override
        public void run() {
            try {
                if (imageViewReused(photoToLoad))
                    return;
                Bitmap bmp = getBitmap(photoToLoad.url);
                memoryCache.put(photoToLoad.url, bmp);
                if (imageViewReused(photoToLoad))
                    return;
                BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
                handler.post(bd);
            } catch (Throwable th) {
                th.printStackTrace();
            }
        }
    }

    boolean imageViewReused(PhotoToLoad photoToLoad) {
        String tag = imageViews.get(photoToLoad.imageView);
        if (tag == null || !tag.equals(photoToLoad.url))
            return true;
        return false;
    }

    // Used to display bitmap in the UI thread
    class BitmapDisplayer implements Runnable {
        Bitmap bitmap;
        PhotoToLoad photoToLoad;

        public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
            bitmap = b;
            photoToLoad = p;
        }

        public void run() {
            if (imageViewReused(photoToLoad))
                return;
            if (bitmap != null)
                photoToLoad.imageView.setImageBitmap(bitmap);
            else
                photoToLoad.imageView.setImageResource(R.drawable.camera_iris);
        }
    }

    public void clearCache() {
        memoryCache.clear();
        fileCache.clear();
    }

}

There is a NullPointerException imageLoader.DisplayImage(phonearraylist.get(position).getPhone(), holder.phone); 有一个NullPointerException imageLoader.DisplayImage(phonearraylist.get(position).getPhone(), holder.phone);

Which leads to a suspiciously null (ImageView) holder.phone . 这导致一个可疑的null (ImageView) holder.phone

Why it must be null ? 为什么必须为null?

Because it might not be lying inside the view you inflated to. 因为它可能不在您放大的视图内。

So 所以

You should check if you are inflating a proper layout from resource and not making any of the most common mistakes like using activity/fragment's layout resource instead of using adapter's item layout. 您应该检查是否从资源中夸大了正确的布局,并且没有犯任何最常见的错误,例如使用活动/片段的布局资源而不是使用适配器的项目布局。

You're welcome. 别客气。

ImageLoader Initialize like below way ImageLoader初始化如下

DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
    .cacheOnDisc()//.imageScaleType(ImageScaleType.EXACTLY)
    .bitmapConfig(Bitmap.Config.RGB_565).build();
    ImageLoaderConfiguration.Builder builder = new ImageLoaderConfiguration.Builder(
            this).defaultDisplayImageOptions(defaultOptions).memoryCache(
                    new WeakMemoryCache());

    Display display = getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    int width = size.x;
    int height = size.y;
    ImageLoaderConfiguration config = builder.build();
    imageLoader = ImageLoader.getInstance();
    imageLoader.init(config);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM