[android] Android get image from gallery into ImageView

I'm trying to add a photo from galery to a ImageView but I get this error:

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

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 the selectedImagePath="mnt/sdcard/DCIM/myimage" but on img.setImageURI(selectedImageUri); i get the error.

I've also used a 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)

Advice please.Thanks!

This question is related to android imageview gallery image-gallery getimagedata

The answer is


Run the app in debug mode and set a breakpoint on if (requestCode == SELECT_PICTURE) and inspect each variable as you step through to ensure it is being set as expected. If you are getting a NPE on img.setImageURI(selectedImageUri); then either img or selectedImageUri are not set.


This is the easiest way to get image from gallery and crop ass well

step 1: StartActivity for 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:Handle 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");
        }
    }


}

@parag's code works great. But while loading some large images you may fail. You should use;

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

instead of;

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

Here are my methods that 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;
}

Here is the code,which 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 Manifest file add

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

i think your ImageView img is not instantiated its equal to null to the compiler; that's why an NullPointerException is raised

did you call in your activity

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

where my_imageview is the id of your ImageView widget!!


parag-chauhan and devrim answers are perfect, but i change the onActivityResult without cursor, and it makes the code much more 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;
}

put below code in button click event

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

put below code in startActivityforResult event

Uri ImagePathAndName = data.getData();
imgpicture.setImageURI(ImagePathAndName);

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

The original answer is that your path has to join prefix like Uri.parse("file://" + file.getPath);


I think the simplest way it's to use library ContentManager. This library for getting photo or video from a device gallery, cloud or camera. With asynchronous load from the cloud and fixed bugs for some problem devices.

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


//try this to pick image from gallery..
    public void gotogallery(View view) { 
// onclick for gallery button
        chooseImage();
    }
// choose image from gallery
          public void chooseImage() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST); //activity result method call
    }

    @Override
    protected void onActivityResult(int requestcode,int resultcode,Intent data ) {
        super.onActivityResult(requestcode, resultcode, data);

        if (requestcode == PICK_IMAGE_REQUEST && resultcode == RESULT_OK && data != null && data.getData() != null) {

            Uri uri = data.getData();

            try {
           Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);


                slectimageview=findViewById(R.id.imageviewimagetopdf_id);
                slectimageview.setImageBitmap(bitmap);


            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }

@Parag Chauhan soltution is working well, but I had problem - some file manager apps are returning in Intent object "file:///..." instead of "content://..." - which is needed to use query.

There is my short solution for that 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 solution,

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

parital solution here (@Nikolay) Get filename and path from URI from mediastore


Simple pass Intent 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 picture 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 full source code here


Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to imageview

How to show imageView full screen on imageView click? How can I show an image using the ImageView component in javafx and fxml? ImageView in circular through xml ImageView rounded corners How to set tint for an image view programmatically in android? how to set image from url for imageView Scale Image to fill ImageView width and keep aspect ratio Change Image of ImageView programmatically in Android How to create a circular ImageView in Android? Full screen background image in an activity How to add an image to the emulator gallery in android studio? Changing image sizes proportionally using CSS? Mosaic Grid gallery with dynamic sized images Android get image from gallery into ImageView android - save image into gallery android pick images from gallery How can I make a horizontal ListView in Android? Android: Bitmaps loaded from gallery are rotated in ImageView Horizontal ListView in Android? Image, saved to sdcard, doesn't appear in Android's Gallery app Select multiple images from android gallery Android get image from gallery into ImageView android get real path by Uri.getPath()

Examples related to getimagedata

Android get image from gallery into ImageView Get pixel color from canvas, on mousemove