nullPointerException with extended SimpleCursorAdapter

百般思念 提交于 2019-12-04 17:00:48

first: get rid of this line:

private Cursor mCursor;

and instead of mCursor use getCursor() since you didnt override swapCursor method and mCursor will be point to the old cursor.

second: change

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

to:

@Override
public int getCount() {
  if(getCursor()==null) 
     return 0; 
  return getCursor().getCount();
}

or better do not override getCount, getItem and getItemId at all

public class ImageAdapter extends SimpleCursorAdapter {
    private int columnIndex;

    private Context mContext;
    private Cursor mCursor;

    private LayoutInflater mInflater;
    private class ViewHolder {
        ImageView imageView;
    }

    public ImageAdapter(Context c, int layout, Cursor aCursor, String[] from,
            int[] to, int flags) {
        super(c, layout, aCursor, from, to, flags);
        this.mContext = c;
        this.mCursor = aCursor;
        mInflater = (LayoutInflater) 
                c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

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

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

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder vh;
        View cell = convertView;
        if (cell == null) {
            vh = new ViewHolder();
            // No View passed, create one.
            cell = mInflater.inflate(R.layout.galleryitem, null);
            // Populate the ViewHolder
            vh.imageView = (ImageView) cell.findViewById(R.id.thumbImage);
            // Store the ViewHolder inside the layout
            cell.setTag(vh);
            // Setup the View behavior by setting some listeners...
        } else {
            vh = (ViewHolder) cell.getTag();
        }
        // Update the cell View state
        // Move the cursor to the current position
        mCursor.moveToPosition(position);
        // Get the current value for the requested position
        columnIndex = mCursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        int imageID = mCursor.getInt(columnIndex);
        // Set the content of the image based on the provided Uri
        vh.imageView.setImageURI(Uri.withAppendedPath(
                MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, "" +
        imageID));
        return cell;
    }    
}

your problem is might because of you do not have initialized you object for Cursor and Context. try the above code. Might Help you.

Needs to pass loader.loadInBackground() in

  mAdapter = new ImageAdapter(getApplication(), R.layout.galleryitem,
                loader.loadInBackground(), cols, views, 0);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!