最近,我制作了一个简单的应用程序,并且我已经被困了一段时间,因为我已经通过网络阅读了一个小问题。
我试图将图像从android中的图库设置为片段中的imageView,但是,每当我选择图像时,应用程序都会关闭。我已经读过这个网站中的类似问题,但解决方案并没有解决我的问题。也许,在不知情的情况下,我可能会以不同的方式设置内容,但我无法看到代码的问题,我在下面设置了示例代码。
((Button) rootView.findViewById(R.id.Button01))
.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
return rootView;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (data != null) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
//I want to set the image in this imageView
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
cursor.close();
} else {
}
答案 0 :(得分:1)
//在manifest.xml文件中使用此权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
//将此代码用于intent ...
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(Intent.createChooser(intent, "Select File"),REQUEST_GET_PHOTO);
// onResultActivity:
if (resultCode == RESULT_OK) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
System.out.println("Get the Image from data");
// Get the cursor
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String imgDecodableString = cursor.getString(columnIndex);
cursor.close();
ImageView imgView = (ImageView) findViewById(R.id.imgView);
// Set the Image in ImageView after decoding the String
imgView.setImageBitmap(BitmapFactory.decodeFile(imgDecodableString));
}