java - Adapter 内的 ImageView 出现 NullPointerException

标签 java android android-layout android-adapter

我正在使用 ViewPager 来保存我的 fragment 。我有两个具有不同解析查询的 fragment 。我的 fragment 之一具有 GridView 布局。我已经为 GridView 创建了适配器来加载图像。

这是我的 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);
        }
    }

}

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

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

当我在另一个只有一个 Fragment 的项目中运行相同的代码时,它可以工作,但是当我在当前项目中使用它时,两个具有不同解析查询的 Fargment 会出现 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();
    }

}

最佳答案

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

这会导致可疑的空(ImageView)holder.phone

为什么它必须为空?

因为它可能不在您膨胀到的 View 内。

所以

您应该检查是否从资源中扩充了正确的布局,并且没有犯任何最常见的错误,例如使用 Activity/fragment 的布局资源而不是使用适配器的项目布局。

不客气。

关于java - Adapter 内的 ImageView 出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36259849/

相关文章:

JavaFX - 按钮不起作用

android - 如何实现像 uber android 一样的可拖动 map ,使用更改位置进行更新

android - 按钮的自定义背景设置不正确

android - 在android中从后台捕获应用程序的返回

Android将图像缩放到屏幕密度

java - Android从xlsx读取数据

java - 运行 CXF JAX WS 服务时出现问题

java - 在 inputStr 上找不到符号

java - 这个 URI URL 有什么问题? IllegalArgumentException,非法字符

android - 带有混淆器的 Ksoap2