Android - 如何从片段中选择和显示图像?

时间:2015-04-20 18:47:28

标签: java android image android-intent android-fragments

我一直在尝试选择并在我的片段上显示图像,但它似乎无法正常工作。

下面我的代码启动并带我到我的画廊,但当我点击图片时,我的应用程序崩溃并在行上给我一个错误:

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

有错误:

  

java.lang.RuntimeException:传递结果失败   ResultInfo {who = null,request = 131073,result = -1,data = Intent {   dat = content:// media / external / images / media / 19394(有额外内容)}}到   activity {com.mycompany.e_planner / com.mycompany.e_planner.MyActivity}:   java.lang.SecurityException:Permission Denial:reading   com.android.providers.media.MediaProvider uri   content:// media / external / images / media / 19394 from pid = 29204,uid = 10011   需要android.permission.READ_EXTERNAL_STORAGE,或   grantUriPermission()

这是我的代码:

public class Venue1 extends Fragment {

private int PICK_IMAGE_REQUEST = 1;

public Venue1() {
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View V = inflater.inflate(R.layout.fragment_venue1, container, false);

    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);

    return V;
}

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

    if (requestCode == PICK_IMAGE_REQUEST && resultCode == Activity.RESULT_OK && data != null && data.getData() != null) {

        Uri uri = data.getData();

        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri);
            // Log.d(TAG, String.valueOf(bitmap));

            ImageView imageView = (ImageView)getActivity().findViewById(R.id.imageView);
            imageView.setImageBitmap(bitmap);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
}

2 个答案:

答案 0 :(得分:0)

嗯,错误是非常自我解释的。您需要申请权限android.permission.READ_EXTERNAL_STORAGE。只需将其添加到manifest file.

即可

答案 1 :(得分:0)

添加读取清单文件中外部存储空间的权限

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