【问题标题】:Can't load image from saved URI in shared preferences无法从共享首选项中保存的 URI 加载图像
【发布时间】:2017-06-18 00:42:01
【问题描述】:

我让用户选择一张图片并将我从该操作收到的 URI 保存在我的共享首选项中。此 URI 将在不同的活动中再次使用。这对于用户选择图像并保存 URI 的一次效果很好,但是当应用程序关闭并再次打开时,当 Activity 尝试加载保存在共享首选项中的 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 始终相同。

【问题讨论】:

  • 我一般使用glide加载共享偏好中保存的图片
  • the app crashes when it tries to open the InputStream。那么你也应该捕获其他异常。你现在有一个 catch 块。但是,如果有问题,您只需继续执行代码,就好像什么都没发生一样。相反,您应该停止。向报告 e.getMessage() 的用户显示敬酒并返回;
  • the program just crashes when the activity tries to load the image of the URI saved in the shared preferences AND the app crashes when it tries to open the InputStream.

标签: android android-intent bitmap uri


【解决方案1】:

从sharedpreference中提取URI后,可以直接将uri设置为imageview,不需要转换成bitmap。

这就是你如何将 uri 设置为 imageView:

    iv.setImageURI(uri);

【讨论】:

  • 用你的代码替换我的代码可以阻止应用程序崩溃,但现在ImageView 只是黑色的并且不加载位图。
  • 你不需要转换成位图,可能返回的uri是空白的或者uri有问题。同样的方法对我有用
【解决方案2】:

uri 的保存过程可能存在问题..

当你保存时

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

它可能将 uri 作为字符串..你可以做一件事..从 uri 中保存路径..like

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

其他一切都将保持不变.. 希望这有效..

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多