android - 即使在用户关闭应用程序后也显示图像
问题描述
即使在用户关闭应用程序后,如何加载用户选择的同一张图片?我目前有以下我调用的代码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();
}
}
解决方案
假设图像实际保存为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.");
}
}
但是,如果图像尚未保存或不存在,那么您可能需要问另一个问题,详细说明您当前的操作方式。但是此设置将让您知道该图像是否确实存在。
推荐阅读
- python - 在 pyttsx3 中使用 32 位语音
- swift - 如何从 Healthkit 中查询每日总步数并显示到 SwiftUI 文本视图中?
- node.js - NerManager(来自 nlp.js)错误地提取了系统(“预训练”)实体等实体
- java - 是否可以使用 Camel 的“计时器”组件中的属性来修改用于定期轮询的 sql 选择(按时间戳)?
- java - 我的应用程序显示“应用程序可能在其主线程上做了太多工作。”,我不知道代码的哪一部分导致了这种情况
- r - 使用 YahooQF 下载股票目标价格
- swift - 你如何让一个枚举可以通过它的案例名称而不是它的原始值来解码?
- javascript - TypeError:this.props.history 不是 Navigation 共享组件中的函数
- ruby-on-rails - 作为可投票的宝石,我将如何显示喜欢/赞成的帖子
- scheme - 谁能解释这段代码中发生了什么?