Domanda

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!

È stato utile?

Soluzione

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.

Altri suggerimenti

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

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

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


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

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

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

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

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" />

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

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


    }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top