我让用户选择一个图像并将我从此操作接收的URI保存在我的共享首选项中。该URI在不同的活动中再次使用。这适用于用户选择图像并保存URI的一次,但是当应用程序关闭并再次打开时,当活动尝试加载保存在共享首选项中的URI的图像时,程序会崩溃。为什么会发生这种情况,为什么在第一次选择图像时工作?无法从共享首选项中保存来自保存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的URI始终相同。
我一般用滑翔加载保存在共享偏好 – Sanjeev
'应用程序崩溃的图像时,它试图打开InputStream'。那么你也应该抓住其他例外。你现在有一个catch块。但是如果有一个问题,就像没有任何事情发生一样,继续使用代码。相反,你应该停止。向报告e.getMessage()的用户显示一个敬酒并返回; – greenapps
当活动尝试加载共享首选项中保存的URI的图像时,程序崩溃并且尝试打开InputStream时应用程序崩溃。 – greenapps