2017-02-01 53 views
1

我让用户选择一个图像并将我从此操作接收的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始终相同。

+0

我一般用滑翔加载保存在共享偏好 – Sanjeev

+0

'应用程序崩溃的图像时,它试图打开InputStream'。那么你也应该抓住其他例外。你现在有一个catch块。但是如果有一个问题,就像没有任何事情发生一样,继续使用代码。相反,你应该停止。向报告e.getMessage()的用户显示一个敬酒并返回; – greenapps

+0

当活动尝试加载共享首选项中保存的URI的图像时,程序崩溃并且尝试打开InputStream时应用程序崩溃。 – greenapps

回答

2

从sharedpreference中提取URI后,您可以直接将uri设置为imageview,而无需将其转换为位图。

这就是你的URI设置为ImageView的:

iv.setImageURI(uri); 
+1

用你的行替换我的代码可以停止应用程序崩溃,但现在'ImageView'只是黑色,并且不会加载位图。 – Jonas

+0

你不需要转换成位图,也许返回的uri是空白的或者uri有问题。同样的方式为我工作 –

0

有可能是在保存过程中问题的URI ..

如你节省

edit.putString(URI, uri.toString()); 

它可能需要uri作为一串。你可以做一件事,那就是保存从uri的路径。如

edit.putString(URI, uri.getPath()); 

一切将保持相同.. 希望在工程..