从Nexus 5(Android 5.1.1)上的图库中挑选图片返回null,在其他设备上工作

时间:2015-06-04 15:25:52

标签: android android-intent gallery onactivityresult nexus-5

我有一个应用程序,它具有允许用户从图库中选择图像的功能。以下是执行此操作的代码:

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

}

onActivityResult方法:

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方法:

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

如果我在我的三星S2上进行测试,它可以正常工作(目前在Cyanogen Mod,Android 4.0.4上),但如果我在Nexus 5(Android 5.1.1)上进行测试,它会返回空指针异常。

注意

我尝试了不同的应用程序:我认为使用Google相册从图库中获取图片可能会导致问题,但我将其安装在我的S2上并且有效。

这是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)

你能帮我解决这个问题吗?

提前致谢,欢呼!

2 个答案:

答案 0 :(得分:1)

A Uri is not a file。您无法可靠地获取用户通过ACTION_GET_CONTENT选择的内容的本地路径。您需要将Uri视为Web服务器的URL,您可以在Uri上打开流,无论是直接(getContentResolver().openInputStream())还是间接(通过Picasso)。

我不知道ImageResizer是什么,但如果它只适用于文件,请停止使用它。删除getPath()方法,仅使用Uri

答案 1 :(得分:1)

而不是从Intent直接传递字符串来自onActivityResult的Uri

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

}