【发布时间】:2017-06-18 00:42:01
【问题描述】:
我让用户选择一张图片并将我从该操作收到的 URI 保存在我的共享首选项中。此 URI 将在不同的活动中再次使用。这对于用户选择图像并保存 URI 的一次效果很好,但是当应用程序关闭并再次打开时,当 Activity 尝试加载保存在共享首选项中的 URI 图像时,程序就会崩溃。为什么会发生这种情况,为什么在第一次选择图像时它会起作用?
这里我让用户选择一张图片并保存收到的 URI:
public void pickImage(View view) {
Intent pickIntent = new Intent();
pickIntent.setType("image/*");
pickIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(pickIntent, 1);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) {
return;
}
if (requestCode == 1) {
Uri uri = data.getData();
SharedPreferences prefs = this.getSharedPreferences(PREFS, MODE_PRIVATE);
SharedPreferences.Editor edit = prefs.edit();
edit.clear();
edit.putString(URI, uri.toString());
edit.commit();
}
}
在这里我再次加载保存在 URI 中的图像:
private void setImage() {
SharedPreferences prefs = this.getSharedPreferences(MainActivity.PREFS, MODE_PRIVATE);
String string_uri = prefs.getString(MainActivity.URI, "not found");
Uri uri = Uri.parse(string_uri);
InputStream inputStream = null;
try {
inputStream = getContentResolver().openInputStream(uri);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap bmp = BitmapFactory.decodeStream(inputStream);
ImageView iv = (ImageView) findViewById(R.id.imageView_card);
iv.setImageBitmap(bmp);
}
调试显示应用在尝试打开 InputStream 时崩溃。我检查了它,用于此的 URI 始终相同。
【问题讨论】:
-
我一般使用glide加载共享偏好中保存的图片
-
the app crashes when it tries to open the InputStream。那么你也应该捕获其他异常。你现在有一个 catch 块。但是,如果有问题,您只需继续执行代码,就好像什么都没发生一样。相反,您应该停止。向报告 e.getMessage() 的用户显示敬酒并返回; -
the program just crashes when the activity tries to load the image of the URI saved in the shared preferencesANDthe app crashes when it tries to open the InputStream.
标签: android android-intent bitmap uri