我在一款Android应用程序中遇到了位图问题。它应该从网站下载图片,将其保存到设备上,将其作为位图加载到ArrayList中,并将其显示给用户。当应用程序首次启动时,所有这些都能够正常工作。然而,我为用户添加了一个刷新选项,其中包括删除图像并重新开始上述过程。
我的问题是:通过使用刷新选项,旧的图像仍然存在于内存中,我很快就会收到OutOfMemoryErrors的错误。因此,如果正在刷新图像,则需要运行数组列表并回收旧图像。但是,当应用程序尝试将新图片加载到ArrayList中时,它会崩溃,并出现“Trying to use recycled bitmap”错误。
据我所知,回收位图会销毁位图并释放其内存以供其他对象使用。如果我想再次使用位图,则必须重新初始化它。我相信当将新文件加载到ArrayList中时,我正在这样做,但仍有问题。非常感谢任何帮助,因为这非常令人沮丧。以下是问题代码。谢谢!
我的问题是:通过使用刷新选项,旧的图像仍然存在于内存中,我很快就会收到OutOfMemoryErrors的错误。因此,如果正在刷新图像,则需要运行数组列表并回收旧图像。但是,当应用程序尝试将新图片加载到ArrayList中时,它会崩溃,并出现“Trying to use recycled bitmap”错误。
据我所知,回收位图会销毁位图并释放其内存以供其他对象使用。如果我想再次使用位图,则必须重新初始化它。我相信当将新文件加载到ArrayList中时,我正在这样做,但仍有问题。非常感谢任何帮助,因为这非常令人沮丧。以下是问题代码。谢谢!
public void fillUI(final int refresh) {
// Recycle the images to avoid memory leaks
if(refresh==1) {
for(int x=0; x<images.size(); x++)
images.get(x).recycle();
images.clear();
selImage=-1; // Reset the selected image variable
}
final ProgressDialog progressDialog = ProgressDialog.show(this, null, this.getString(R.string.loadingImages));
// Create the array with the image bitmaps in it
new Thread(new Runnable() {
public void run() {
Looper.prepare();
File[] fileList = new File("/data/data/[package name]/files/").listFiles();
if(fileList!=null) {
for(int x=0; x<fileList.length; x++) {
try {
images.add(BitmapFactory.decodeFile("/data/data/[package name]/files/" + fileList[x].getName()));
} catch (OutOfMemoryError ome) {
Log.i(LOG_FILE, "out of memory again :(");
}
}
Collections.reverse(images);
}
fillUiHandler.sendEmptyMessage(0);
}
}).start();
fillUiHandler = new Handler() {
public void handleMessage(Message msg) {
progressDialog.dismiss();
}
};
}
->}