Android gets image from gallery in ImageView

I try to add a photo from the gallery to ImageView , but I get this error:

java.lang.RuntimeException: rejection of the result ResultInfo {who = null, request = 1, result = -1, data = Intent {dat = content: // media / external / images / media / 1}} to the action {HotMetter. pack / hotMetter.pack.GetPhoto}: java.lang.NullPointerException

This is my code:

  Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE); } Bitmap bitmap=null; public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == Activity.RESULT_OK) { if (requestCode == SELECT_PICTURE) { Uri selectedImageUri = data.getData(); selectedImagePath = getPath(selectedImageUri); tv.setText(selectedImagePath); img.setImageURI(selectedImageUri); } } public String getPath(Uri uri) { String[] projection = { MediaStore.Images.Media.DATA }; Cursor cursor = managedQuery(uri, projection, null, null, null); if (cursor == null) return null; int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); String s=cursor.getString(column_index); cursor.close(); return s; } 

I get selectedImagePath="mnt/sdcard/DCIM/myimage" , but on img.setImageURI(selectedImageUri); I get an error.

I also used Bitmap and tried to set the image from SetImageBitmap , but I get the same error.

LogCat:

 05-06 19:41:34.191: E/AndroidRuntime(8466): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content://media/external/images/media/1 }} to activity {hotMetter.pack/hotMetter.pack.GetPhoto}: java.lang.NullPointerException 05-06 19:41:34.191: E/AndroidRuntime(8466): at android.app.ActivityThread.deliverResults(ActivityThread.java:2532) 05-06 19:41:34.191: E/AndroidRuntime(8466): at android.app.ActivityThread.handleSendResult(ActivityThread.java:2574) 05-06 19:41:34.191: E/AndroidRuntime(8466): at android.app.ActivityThread.access$2000(ActivityThread.java:117) 05-06 19:41:34.191: E/AndroidRuntime(8466): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:961) 05-06 19:41:34.191: E/AndroidRuntime(8466): at android.os.Handler.dispatchMessage(Handler.java:99) 05-06 19:41:34.191: E/AndroidRuntime(8466): at android.os.Looper.loop(Looper.java:123) 05-06 19:41:34.191: E/AndroidRuntime(8466): at android.app.ActivityThread.main(ActivityThread.java:3683) 05-06 19:41:34.191: E/AndroidRuntime(8466): at java.lang.reflect.Method.invokeNative(Native Method) 05-06 19:41:34.191: E/AndroidRuntime(8466): at java.lang.reflect.Method.invoke(Method.java:507) 05-06 19:41:34.191: E/AndroidRuntime(8466): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839) 05-06 19:41:34.191: E/AndroidRuntime(8466): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) 05-06 19:41:34.191: E/AndroidRuntime(8466): at dalvik.system.NativeStart.main(Native Method) 05-06 19:41:34.191: E/AndroidRuntime(8466): Caused by: java.lang.NullPointerException 05-06 19:41:34.191: E/AndroidRuntime(8466): at hotMetter.pack.GetPhoto.onActivityResult(GetPhoto.java:55) 05-06 19:41:34.191: E/AndroidRuntime(8466): at android.app.Activity.dispatchActivityResult(Activity.java:3908) 05-06 19:41:34.191: E/AndroidRuntime(8466): at android.app.ActivityThread.deliverResults(ActivityThread.java:2528) 

Please advise. Thank!

+52
android imageview image-gallery gallery getimagedata
May 6 '12 at 20:03
source share
13 answers

Run the application in debug mode and set a breakpoint if (requestCode == SELECT_PICTURE) and check each variable as it passes to make sure that it is configured as expected. If you get NPE on img.setImageURI(selectedImageUri); then img or selectedImageUri not set.

+8
May 6 '12 at 20:38
source share

Intent simple pass first:

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

And you will get the image path on your onActivityResult :

 @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) { Uri selectedImage = data.getData(); String[] filePathColumn = { MediaStore.Images.Media.DATA }; Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null); cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(filePathColumn[0]); String picturePath = cursor.getString(columnIndex); cursor.close(); ImageView imageView = (ImageView) findViewById(R.id.imgView); imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath)); } } 

for the full source code here

+110
May 6 '12 at 20:47
source share

Try the following:

 import java.io.FileDescriptor; import java.io.IOException; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.os.ParcelFileDescriptor; import android.provider.MediaStore; import android.view.View; import android.widget.Button; import android.widget.ImageView; public class ImageGalleryDemoActivity extends Activity { private static int RESULT_LOAD_IMAGE = 1; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadPicture); buttonLoadImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { Intent i = new Intent( Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(i, RESULT_LOAD_IMAGE); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) { Uri selectedImage = data.getData(); String[] filePathColumn = { MediaStore.Images.Media.DATA }; Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null); cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(filePathColumn[0]); String picturePath = cursor.getString(columnIndex); cursor.close(); ImageView imageView = (ImageView) findViewById(R.id.imgView); Bitmap bmp = null; try { bmp = getBitmapFromUri(selectedImage); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } imageView.setImageBitmap(bmp); } } private Bitmap getBitmapFromUri(Uri uri) throws IOException { ParcelFileDescriptor parcelFileDescriptor = getContentResolver().openFileDescriptor(uri, "r"); FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor(); Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor); parcelFileDescriptor.close(); return image; } } 
+18
Nov 01 '15 at 13:17
source share

@Parag code works fine. But when you upload some large images you may fail. You must use;

 imageView.setImageBitmap(getScaledBitmap(picturePath, 800, 800)); 

instead;

 imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath)); 

Here are my methods you can use.

 private Bitmap getScaledBitmap(String picturePath, int width, int height) { BitmapFactory.Options sizeOptions = new BitmapFactory.Options(); sizeOptions.inJustDecodeBounds = true; BitmapFactory.decodeFile(picturePath, sizeOptions); int inSampleSize = calculateInSampleSize(sizeOptions, width, height); sizeOptions.inJustDecodeBounds = false; sizeOptions.inSampleSize = inSampleSize; return BitmapFactory.decodeFile(picturePath, sizeOptions); } private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { // Raw height and width of image final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { // Calculate ratios of height and width to requested height and // width final int heightRatio = Math.round((float) height / (float) reqHeight); final int widthRatio = Math.round((float) width / (float) reqWidth); // Choose the smallest ratio as inSampleSize value, this will // guarantee // a final image with both dimensions larger than or equal to the // requested height and width. inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; } return inSampleSize; } 
+16
Jul 08 '13 at 17:53
source share

This is the easiest way to get an image from the gallery and crop the donkey.

step 1: StartActivity for the result

 imageUser.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI); intent.setType("image/*"); intent.putExtra("crop", "true"); intent.putExtra("scale", true); intent.putExtra("outputX", 256); intent.putExtra("outputY", 256); intent.putExtra("aspectX", 1); intent.putExtra("aspectY", 1); intent.putExtra("return-data", true); startActivityForResult(intent, 1); } }); 

step 2: process the result

 @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode != RESULT_OK) { return; } if (requestCode == 1) { final Bundle extras = data.getExtras(); if (extras != null) { //Get image Bitmap ProfilePic = extras.getParcelable("data"); imageUser.setImageBitmap(ProfilePic); TextView t=(TextView)findViewById(R.id.textoverimage); t.setText("image Selected"); } } } 
+11
Jun 22 '16 at 11:18
source share

I think the easiest way to use the ContentManager library. This library is for retrieving photos or videos from a device’s gallery, cloud or camera. With asynchronous load from the cloud and fixed errors for some problematic devices.

Download via Gradle: compile 'com.github.stfalcon:contentmanager:0.4.3' You can find the documentation at https://github.com/stfalcon-studio/ContentManager

+2
Feb 24 '17 at 12:12
source share
 import android.content.Intent; import android.net.Uri; import android.provider.MediaStore; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.ImageView; public class MainActivity extends AppCompatActivity { ImageView img; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); img = (ImageView)findViewById(R.id.imageView); } public void btn_gallery(View view) { Intent intent =new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI); startActivityForResult(intent,100); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode==100 && resultCode==RESULT_OK) { Uri uri = data.getData(); img.setImageURI(uri); } } } 
+2
Dec 15 '17 at 18:42 on
source share

I think your ImageView img was not created equal to zero by the compiler; why a NullPointerException occurs

You called your business

 img = (ImageView) findViewById(R.id.my_imageview); 

where my_imageview is the id of your ImageView widget!

+1
May 7 '12 at
source share

The original answer is that your path must be connected with a prefix like Uri.parse ("file: //" + file.getPath);

+1
Aug 21 '15 at 12:38
source share

Here is the code that worked for me.

 Button buttonLoadImage = (Button) findViewById(R.id.button4); buttonLoadImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI); intent.setType("image/*"); intent.putExtra("crop", "true"); intent.putExtra("scale", true); intent.putExtra("outputX", 256); intent.putExtra("outputY", 256); intent.putExtra("aspectX", 1); intent.putExtra("aspectY", 1); intent.putExtra("return-data", true); startActivityForResult(intent, 1);}}); @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode != RESULT_OK) { if (requestCode == RESULT_LOAD_IMAGE && data != null) { Uri imageUri = data.getData(); imageView = (ImageView) findViewById(R.id.imgView); imageView.setImageURI(imageUri);}}} 

in the manifest file add

 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> 
+1
Jan 12 '17 at 5:12
source share

enter the code below in the button click event

 Intent ImageIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); //implicit intent UploadImage.this.startActivityForResult(ImageIntent,99); 



enter below code in startActivityforResult event

 Uri ImagePathAndName = data.getData(); imgpicture.setImageURI(ImagePathAndName); 
+1
Jan 30 '17 at 23:45
source share

@Parag Chauhan soltution works well, but I had a problem - some file manager applications return to the Intent object "file: /// ..." instead of "content: // ..." - which is necessary to use the request.

There is my short solution for this problem:

 public String getRealPathFromURI(Context context, Uri contentUri) { Cursor cursor = null; try { if("content".equals(contentUri.getScheme())) { String[] proj = {MediaStore.Images.Media.DATA}; cursor = context.getContentResolver().query(contentUri, proj, null, null, null); int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); return cursor.getString(column_index); } else{ return contentUri.getPath(); } } finally { if (cursor != null) { cursor.close(); } } } 

Based on @Parag's solution,

partial solution here (@nobre) Android: Getting file URI from content URI?

solution for solving palette (@Nikolay) Get file name and path from URI from mediastar

0
Jul 22 '14 at 10:26
source share

parag-chauhan and devrim answers are perfect, but I change onActivityResult without a cursor, and this makes the code much better.

 @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && data != null) { Uri selectedImage = data.getData(); try { ImageView imageView = (ImageView) findViewById(R.id.imgView); imageView.setImageBitmap(getScaledBitmap(selectedImage,800,800)); } catch (FileNotFoundException e) { e.printStackTrace(); } } } private Bitmap getScaledBitmap(Uri selectedImage, int width, int height) throws FileNotFoundException { BitmapFactory.Options sizeOptions = new BitmapFactory.Options(); sizeOptions.inJustDecodeBounds = true; BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, sizeOptions); int inSampleSize = calculateInSampleSize(sizeOptions, width, height); sizeOptions.inJustDecodeBounds = false; sizeOptions.inSampleSize = inSampleSize; return BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, sizeOptions); } private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { // Raw height and width of image final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { // Calculate ratios of height and width to requested one final int heightRatio = Math.round((float) height / (float) reqHeight); final int widthRatio = Math.round((float) width / (float) reqWidth); // Choose the smallest ratio as inSampleSize value inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; } return inSampleSize; } 
0
Sep 12 '17 at 5:25 on
source share



All Articles