在我的MainActivity onCreate()
我想填充一个列表视图。该列表视图包含字符串和位图。Android在应用程序上下文中保存图像
当应用程序重新启动时,保存这些数据以让它们恢复的最佳方式是什么?
在我的MainActivity onCreate()
我想填充一个列表视图。该列表视图包含字符串和位图。Android在应用程序上下文中保存图像
当应用程序重新启动时,保存这些数据以让它们恢复的最佳方式是什么?
有我自己的缓存解决方案:
public class MyCache {
private String DiretoryName;
public void OpenOrCreateCache(Context _context, String _directoryName){
File file = new File(_context.getCacheDir().getAbsolutePath() + "/" + _directoryName);
if(!file.exists()){
file.mkdir();
}
DiretoryName = file.getAbsolutePath();
}
public void SaveBitmap(String fileName, Bitmap bmp){
try {
File file = new File(DiretoryName+ "/" + fileName);
if(file.exists()){
file.delete();
}
FileOutputStream Filestream = new FileOutputStream(DiretoryName + "/" + fileName);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] byteArray = stream.toByteArray();
Filestream.write(byteArray);
Filestream.close();
bmp.recycle();
}
catch (Exception e){
e.printStackTrace();
}
}
public Bitmap OpenBitmap(String name){
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
File file = new File(DiretoryName+ "/" + name);
if(file.exists()) {
Bitmap bitmap = BitmapFactory.decodeFile(DiretoryName+ "/" + name, options);
return bitmap;
}
else{
return null;
}
}
catch (Exception e){
e.printStackTrace();
}
return null;
}
public void CleanCacheBitMap(){
File file = new File(Diretorio);
if(file.exists()){
file.delete();
}
}
}
而且的onCreate:
@Override
protected void onCreate(Bundle savedInstanceState) {
...
cache = new MyCache();
cache.OpenOrCreateCache(this, "TheFolderNameForOpenOrSaveInAppCache");
}
并为节省运行时间:
cache.SaveBitmap("BitMapName", YourBitmap);
并开通运行时:
Bitmap bmp = cache.OpenBitmap("BitMapName");
此解决方案保存任何位图,特别是应用程序缓存(内部存储)中的文件夹。
我以你的例子为导向,它工作得很好。只有一些重大变化。此外,我不回收bmp以将其保存在内存中一段时间。无论如何,感谢您指点我正确的方向。 – sampa
根据你想要挂在这些文件上的程度有多种可能性。最可靠的方法是getFilesDir()。每个应用程序都有自己的专用“文件目录”。
所有的细节在这里: https://developer.android.com/training/basics/data-storage/files.html
缓存目录(getCacheDir())相似,但用户可以清除缓存内容,以便更适合你不想挂到临时文件。
字符串和位图都可以保存到文件。您可以创建自己的名称值映射文件来链接它们。或者使用JSON对象或许多其他的东西来组织你的字符串/位图的列表。
你最初如何填充它? –
还没有。在查询提交后,列表视图当前已填充。但是我想存储最后查询结果的结果(包括图像),以在应用程序重新启动后显示它们。 – sampa
@sampa使用SharedPreferences来保存一个简单的数据对象。在你的情况下,你可以在那里保存SQL查询。 –