首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Android延迟加载图像类耗尽了我所有的内存

问Android延迟加载图像类耗尽了我所有的内存
EN

Stack Overflow用户
提问于 2011-12-08 09:01:55
回答 1查看 707关注 0票数 1

我正在使用在这里找到的流行的延迟加载类:http://stackoverflow.com/questions/541966/android-how-do-i-do-a-lazy-load-of-images-in-listview/3068012#3068012

我遇到的问题是,我在多个活动中使用了这个类。在活动之间来回导航(加载图片)最终会导致我的应用程序崩溃,出现以下错误:

代码语言:javascript
复制
12-07 19:54:42.414: W/dalvikvm(1204): threadid=91: thread exiting with uncaught exception (group=0x4001b188)
12-07 19:54:42.424: E/AndroidRuntime(1204): Uncaught handler: thread Thread-47 exiting due to uncaught exception
12-07 19:54:42.434: E/AndroidRuntime(1204): java.lang.OutOfMemoryError: bitmap size exceeds VM budget
12-07 19:54:42.434: E/AndroidRuntime(1204):     at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)
12-07 19:54:42.434: E/AndroidRuntime(1204):     at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:459)
12-07 19:54:42.434: E/AndroidRuntime(1204):     at de.tablayoutexample.ImageLoader.decodeFile(ImageLoader.java:124)
12-07 19:54:42.434: E/AndroidRuntime(1204):     at de.tablayoutexample.ImageLoader.getBitmap(ImageLoader.java:78)
12-07 19:54:42.434: E/AndroidRuntime(1204):     at de.tablayoutexample.ImageLoader.access$0(ImageLoader.java:73)
12-07 19:54:42.434: E/AndroidRuntime(1204):     at de.tablayoutexample.ImageLoader$PhotosLoader.run(ImageLoader.java:182)

下面的代码是ImageLoader类的一部分,我怀疑它是罪魁祸首。最初,REQUIRED_SIZE设置为70,这太小了。我将其设置为200,这会使图像质量更好,但会更快地使应用崩溃。

这种延迟加载方法不是应该在用户每次离开活动时都清理图像吗?每次我在另一个活动中加载更多的图片时,它似乎只是在堆积起来。

我是android编程的新手,所以也许有人可以帮我优化这段代码。

代码语言:javascript
复制
 //decodes image and scales it to reduce memory consumption
    private Bitmap decodeFile(File f){
        try {
            //decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new FileInputStream(f),null,o);

            //Find the correct scale value. It should be the power of 2.
            final int REQUIRED_SIZE=200;
            int width_tmp=o.outWidth, height_tmp=o.outHeight;
            int scale=1;
            while(true){
                if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
                    break;
                width_tmp/=2;
                height_tmp/=2;
                scale*=2;
            }

            //decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize=scale;
            return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
        } catch (FileNotFoundException e) {}
        return null;
    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-12-08 09:58:56

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8424876

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档