3

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

これは問題ないように思えますが、プログラムを実行するとクラッシュし、次のエラー メッセージが表示されます。

java.util.concurrent.ExecutionException: java.lang.NullPointerException: null オブジェクト参照で仮想メソッド 'java.lang.String android.net.Uri.getScheme()' を呼び出そうとしています

それで、問題が検出されました。私のプログラムが不平を言う行は次のとおりです。

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

原因と解決策は?

4

1 に答える 1

2

Cursor.getNotificationUri()メソッドを誤解しているようです。
返されたビットマップの URI を取得しようとしていると思います。
それが本当なら、これを試してください:

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;
        }
于 2015-08-15T19:13:19.177 に答える