Vlad Iancu
Vlad Iancu

Reputation: 487

Picking image from gallery on Nexus 5 (Android 5.1.1) returning null, working on other devices

I have an app which has a function that allows the user to pick an image from gallery. Here is the code for doing that:

@OnClick(R.id.imageView_fragmentUploadLayout_uploadedArt)
public void setUploadedArtImageView () {
    //startActivityForResult(new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI), GET_FROM_GALLERY);
    Intent intent = new Intent();
// Show only images, no videos or anything else
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
// Always show the chooser (if there are multiple options available)
    startActivityForResult(Intent.createChooser(intent, "Select Picture"), GET_FROM_GALLERY);

}

And the onActivityResult method:

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    //Detects request codes
    if(requestCode == GET_FROM_GALLERY && resultCode == Activity.RESULT_OK && data != null) {
        selectedImageUri = data.getData();
        selectedImagePath = getPath(selectedImageUri);

        file = new File(selectedImagePath);

        //ParseFile parseImage = new ParseFile();

        Picasso.with(getActivity())
                .load(selectedImageUri.toString())
                .resize(500, 500)
                .centerCrop()
                .noPlaceholder()
                .into(uploadedArtImageView);

        uploadedArtImageViewPlaceHolder.setVisibility(View.GONE);

        ImageResizer.resize(file, 640, 480, ResizeMode.FIT_EXACT);
    }
}

getPath method:

public String getPath(Uri uri) {
    // just some safety built in
    if( uri == null ) {
        // TODO perform some logging or show user feedback
        return null;
    }
    // try to retrieve the image from the media store first
    // this will only work for images selected from gallery
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = getActivity().managedQuery(uri, projection, null, null, null);
    if( cursor != null ){
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }
    // this is our fallback here
    return uri.getPath();
}

If i test it on my Samsung S2 it works, (currently on Cyanogen Mod, Android 4.0.4), but if i test it on the Nexus 5 (Android 5.1.1) it return null pointer exception.

NOTE

I have tried different apps: I thought that getting the picture from the gallery with Google Photos might have cause the problem, but I installed it on my S2 and it works.

Here is the stacktrace:

java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=131075, result=-1, data=Intent { dat=content://com.android.providers.media.documents/document/image:25147 flg=0x1 }} to activity {com.entu.artapp/com.entu.artapp.activity.FragmentManager}: java.lang.NullPointerException: Attempt to invoke virtual method 'char[] java.lang.String.toCharArray()' on a null object reference
   at android.app.ActivityThread.deliverResults(ActivityThread.java:3574)
   at android.app.ActivityThread.handleSendResult(ActivityThread.java:3617)
   at android.app.ActivityThread.access$1300(ActivityThread.java:151)
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1352)
   at android.os.Handler.dispatchMessage(Handler.java:102)
   at android.os.Looper.loop(Looper.java:135)
   at android.app.ActivityThread.main(ActivityThread.java:5254)
   at java.lang.reflect.Method.invoke(Method.java)
   at java.lang.reflect.Method.invoke(Method.java:372)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'char[] java.lang.String.toCharArray()' on a null object reference
   at java.io.File.fixSlashes(File.java:185)
   at java.io.File.<init>(File.java:134)
   at com.entu.artapp.fragments.UploadPictureFragment.onActivityResult(UploadPictureFragment.java:363)
   at android.support.v4.app.FragmentActivity.onActivityResult(FragmentActivity.java:163)
   at android.app.Activity.dispatchActivityResult(Activity.java:6192)
   at android.app.ActivityThread.deliverResults(ActivityThread.java:3570)
   at android.app.ActivityThread.handleSendResult(ActivityThread.java:3617)
   at android.app.ActivityThread.access$1300(ActivityThread.java:151)
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1352)
   at android.os.Handler.dispatchMessage(Handler.java:102)
   at android.os.Looper.loop(Looper.java:135)
   at android.app.ActivityThread.main(ActivityThread.java:5254)
   at java.lang.reflect.Method.invoke(Method.java)
   at java.lang.reflect.Method.invoke(Method.java:372)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

Can you help me with this problem?

Thanks in advance, cheers!

Upvotes: 2

Views: 1909

Answers (2)

Vivek Faldu
Vivek Faldu

Reputation: 336

Instead of passing The String from the Intent Directly Pass the Uri from onActivityResult

MainActivity.class

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);

    Uri imageuri=data.getData();

Intent i=new Intent(MainActivity.this,NextActivity.class);
i.putExtra("uri","imageuri");
startActivity(i);
}

NextActivtiy.class

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_next);

    Uri geturi=getIntent().getParcelableExtra("imageuri");
    InputStream is=null;
    try {
        is = getContentResolver().openInputStream(geturi);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    Bitmap bitmap=BitmapFactory.decodeStream(is);
    //Use this bitmap where you want to display the image

}

Upvotes: 1

CommonsWare
CommonsWare

Reputation: 1006944

A Uri is not a file. You cannot reliably get a local path to something the user picks via ACTION_GET_CONTENT. You need to treat the Uri like a URL to a Web server, where you open streams on the Uri, whether directly (getContentResolver().openInputStream()) or indirectly (via Picasso).

I do not know what ImageResizer is, but if it only works with files, stop using it. Delete your getPath() method and work solely with the Uri.

Upvotes: 1

Related Questions