简体   繁体   中英

Intent data is null in onActivityResult when I pick an Image from gallery

I need to get an Image from the gallery, and transform it into a bitmap.

This is the code for sending the Intent :

Intent i = new Intent(
                Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(i, RESULT_LOAD_IMAGE);

onActivityResult :

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == mResultLoadImage && resultCode == RESULT_OK && data != null) {
            Uri pickedImage = data.getData();
            String[] filePath = { MediaStore.Images.Media.DATA };
            Cursor cursor = getContentResolver().query(pickedImage, filePath,
                    null, null, null);
            cursor.moveToFirst();
            String imagePath = cursor.getString(cursor
                    .getColumnIndex(filePath[0]));
            bitmap = BitmapFactory.decodeFile(imagePath);
            someFunction(bitmap);
            cursor.close();
        }
}

I get always a NullPointerException, and with the debuger, I found out that the data Intent is null. Any solutions?

Try this, it should work:

Intent intent = new Intent(Intent.ACTION_PICK);
startActivityForResult(intent, RESULT_LOAD_IMAGE);

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == RESULT_LOAD_IMAGE) {
        Uri imageUri = data.getData();
        Bitmap imgBitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri), null, null);
        // then do whatever you want with the bitmap
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM