从片段中选择图像始终在某些设备中返回结果码0

时间:2015-09-23 16:54:51

标签: android android-fragments android-intent android-gallery onactivityresult

我尝试从图库中选择一个图像并将位图设置为我的imageview,但我遇到了一个问题:在我的设备中,效果很好,但在其他设备中无效。

我在片段中启动图像选择器,如下所示:

Intent photoPickerIntent = new Intent(Intent.ACTION_PICK); photoPickerIntent.setType("image/*"); startActivityForResult(photoPickerIntent, SELECT_PHOTO);

这是我的onActivityResult

@Override 
public void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) { 

         super.onActivityResult(requestCode, resultCode, imageReturnedIntent); 

         Log.d("ResultCode",resultCode+"");

         switch (requestCode) { 

               case SELECT_PHOTO:
                     if (resultCode == Activity.RESULT_OK) { 
                             Uri selectedImage = imageReturnedIntent.getData(); 
                             try { 
                                    Bitmap imagen = decodeUri(selectedImage);

                                     // Works on my device (because resultCode = RESULT_OK) but doesn't work in others (because resultCode = 0)
                                    ((ImageView) findViewById(R.id.myimage)).setImageBitmap(imagen); 

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

我会感激任何帮助,我有点绝望。 X_X

1 个答案:

答案 0 :(得分:5)

我遇到过这个问题......非常有趣。有三种不同的方式可以选择照片,就像你说的那样,由于某种原因,它并不总能在所有设备上正常工作。经过几个小时的折磨,我发现这一点始终如一:

 Intent intent = new Intent();
 intent.setAction(Intent.ACTION_GET_CONTENT);
 intent.setType("image/*");
 startActivityForResult(Intent.createChooser(intent,"whatever you want",1);

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

       case 1:

            if (resultCode == RESULT_OK)
            {
                Uri selectedImage = data.getData();
            }
            break;
    }
 }