Android gives nullpointer on retrieving images

321 Views Asked by At

I am making an app that picks 3 images of the gallery with an AsyncTask. The content of my AsyncTask> is:

public class ShoppingGallery extends AsyncTask<Void, Void, List<Bitmap>> {
    private Activity activity;
    private static final String LOG_TAG = ShoppingGallery.class.getSimpleName();

    private Uri uri = MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI;
    private String[] projection = {MediaStore.Images.Thumbnails.DATA};
    private Cursor imageCursor;

    public ShoppingGallery(Activity activity){
        this.activity = activity;
        imageCursor = activity.getContentResolver().query(uri, projection, null, null, null);
    }
@Override
    protected List<Bitmap> doInBackground(Void... params) {

    List<Bitmap> imgs = new ArrayList<>();
    while(imageCursor.moveToNext()){
        try {
            if(imgs.size() < 3)
            imgs.add(MediaStore.Images.Media.getBitmap(activity.getContentResolver(), imageCursor.getNotificationUri()));
        } catch (IOException e) {
            Log.e(LOG_TAG, "problem with the image loading: " + e);
        }
    }
    return imgs;
}

Which seems ok for me, but when I run my program it crashes and gives following error message: 08-13 11:14:11.662 22360-22360/com.example.jonas.shoppinglist E/ShoppingContacts﹕ image execution failed:

java.util.concurrent.ExecutionException: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getScheme()' on a null object reference

So, problem detected. The line where my program complains about is:

imgs.add(MediaStore.Images.Media.getBitmap(activity.getContentResolver(), imageCursor.getNotificationUri()));

What is the source and the solution?

1

There are 1 best solutions below

2
On BEST ANSWER

You seem to misunderstand of Cursor.getNotificationUri() method.
I guess that you are trying to get the uries of the returned bitmaps.
If that true, try this:

if (imgs.size() < 3) {
            String uriStr = imageCursor.getString(0);
            Uri uri = null;
            if (uriStr == null)
                continue;
            try {
                uri = Uri.parse(uriStr);
            } catch (Exception e) {
                // log exception
            }
            if (uri == null)
                continue;
            Bitmap bm = null;
            try {
                bm =
                        MediaStore.Images.Media.getBitmap(activity
                                .getContentResolver(), uri);
            } catch (IOException e) {
                // log exception
            }
            if (bm == null)
                continue;
            imgs.add(bm);
            if (imgs.size() == 3)
                break;
        }