簡體   English   中英

無法從共享首選項中的已保存URI加載圖像

[英]Can't load image from saved URI in shared preferences

我讓用戶選擇一個圖像,並將通過此操作收到的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始終是相同的。

從sharedpreference中提取URI后,您可以直接將uri設置為imageview,而無需將其轉換為位圖。

這是將uri設置為imageView的方法:

    iv.setImageURI(uri);

uri的保存過程可能存在問題。

當您保存時

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

它可以將uri作為字符串。.您可以做一件事..保存uri的路徑。

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

一切都將保持不變..希望這項工作..

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM