2017-02-01 55 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()); 

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