适配器内部imageview上的nullpointerexception

h22fl7wq  于 2021-07-13  发布在  Java
关注(0)|答案(2)|浏览(314)

我用viewpager来保存我的片段。我有两个具有不同解析查询的片段。我的一个片段有网格视图布局。我已经为gridview创建了一个适配器来加载图像。
这是我的碎片

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

}

我创建的适配器将图像加载到

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;
    }
}

这里它给了我imageloader.displayimage(phonearraylist.get(position.getphone(),holder.phone)上的nullpointerexception;
当我在另一个项目中运行同一个代码时,只有一个片段可以工作,但当我在当前项目中使用它时,两个片段有不同的解析查询,它会给我nullpointerexception。请帮助我在这方面浪费了大约5天的时间,让它工作在我的最后尝试了一切可能的方法。
这是我的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();
    }

}
rqmkfv5c

rqmkfv5c1#

存在nullpointerexception imageLoader.DisplayImage(phonearraylist.get(position).getPhone(), holder.phone); 这导致了一个可疑的空值 (ImageView) holder.phone .
为什么必须为空?
因为它可能不在你膨胀到的视野之内。
所以
您应该检查是否从资源中膨胀了正确的布局,并且没有犯任何最常见的错误,例如使用活动/片段的布局资源而不是使用适配器的项布局。
不客气。

nhjlsmyf

nhjlsmyf2#

图像加载程序如下所示

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);

相关问题