我讓用戶選擇一個圖像並將我從此操作接收的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