Android在检索图像时提供nullpointer

时间:2015-08-13 09:19:52

标签: java android android-asynctask image-gallery executionexception

我正在创建一个应用程序,使用AsyncTask选择3个图库。 我的AsyncTask的内容>是:

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

这对我来说似乎没问题,但是当我运行我的程序时它会崩溃并发出以下错误消息: 08-13 11:14:11.662 22360-22360 / com.example.jonas.shoppinglist E / ShoppingContacts:图像执行失败:

  

java.util.concurrent.ExecutionException:   java.lang.NullPointerException:尝试调用虚方法   &#39; java.lang.String android.net.Uri.getScheme()&#39;在null对象上   参考

因此,检测到问题。我的程序抱怨的行是:

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

来源和解决方案是什么?

1 个答案:

答案 0 :(得分:2)

您似乎误解了Cursor.getNotificationUri()方法 我想你正试图得到返回位图的嘶嘶声 如果是这样,试试这个:

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