【发布时间】: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