首页 > 解决方案 > 即使在用户关闭应用程序后也显示图像

问题描述

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

 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();
        }

    }

标签: androiddynamicimageviewandroid-internal-storage

解决方案


假设图像实际保存为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.");
    }

}

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


推荐阅读