【问题标题】:Display an image even after the user has closed the app即使在用户关闭应用程序后也显示图像
【发布时间】:2019-08-01 00:47:09
【问题描述】:

即使在用户关闭应用后,如何加载用户选择的同一张图片? 我目前有以下代码,我在onCreate 中调用,但每次用户关闭应用程序时Bitmap 为空。

 private void loadImageFromStorage() {

        ContextWrapper cw = new ContextWrapper(getApplicationContext());
        File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
        File myPath = new File(directory,"profile.jpg");

        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(myPath);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            File f = new File(directory.getAbsolutePath(), "profile.jpg");
            Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
            ImageView coverView = findViewById(R.id.cover_view);
            coverView.setImageBitmap(b);
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

【问题讨论】:

  • 如果应用程序关闭,您将在哪里显示图像?这没有任何意义。
  • 将“图像文件路径”保存在 SharedPreferences 中,并在用户下次打开应用时(在 onCreate 中)检索它。

标签: android dynamic imageview android-internal-storage


【解决方案1】:

假设图像实际保存为profile.jpg 并且存在于imageDir 文件夹中,则加载图像所需要做的就是(根据您当前的使用情况):

private void loadImageFromStorage() {

    ContextWrapper cw = new ContextWrapper(getApplicationContext());
    File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
    File myFile = new File(directory.getAbsolutePath(),"profile.jpg");

    if(myFile.exists()){
        try {
            Bitmap b = BitmapFactory.decodeFile(myFile.getAbsolutePath());
            ImageView coverView = findViewById(R.id.cover_view);
            coverView.setImageBitmap(b);
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        Log.d("MyApp", "The image file does not exist.");
    }

}

但如果图像尚未保存或不存在,那么您可能需要提出另一个问题,详细说明您当前的操作方式。但是这种设置可以让您知道该图像是否真的存在。

【讨论】:

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