【问题标题】:java.lang.OutOfMemoryError: bitmap size exceeds VM budgetjava.lang.OutOfMemoryError:位图大小超出 VM 预算
【发布时间】:2011-04-26 18:46:28
【问题描述】:

所以我的ListView 有一个惰性图像加载器。我还使用this tutorial 进行更好的内存管理,并将SoftReference 位图图像存储在我的ArrayList 中。

我的ListView 作品从数据库加载 8 张图片,然后一旦用户一直滚动到底部,它就会加载另外 8 张等。当大约 35 张或更少的图片时没有问题,但我的更多应用程序强制关闭OutOfMemoryError

我无法理解的是我的代码在 try catch 中:

try
{
    BitmapFactory.Options o = new BitmapFactory.Options();
    o.inJustDecodeBounds = true;
    BitmapFactory.decodeByteArray(image, 0, image.length, o);

    //Find the correct scale value. It should be the power of 2.
    int width_tmp = o.outWidth, height_tmp = o.outHeight;
    int scale = 1;

    while(true)
    {
        if(width_tmp/2 < imageWidth || height_tmp/2 < imageHeight)
        {
            break;
        }

        width_tmp/=2;
        height_tmp/=2;
        scale++;
    }

    //Decode with inSampleSize
    BitmapFactory.Options o2 = new BitmapFactory.Options();
    o2.inSampleSize = scale;
    bitmapImage = BitmapFactory.decodeByteArray(image, 0, image.length, o2);        
}
catch (Exception e)
{
    e.printStackTrace();
}

但是 try catch 块没有捕捉到OutOfMemory 异常,据我了解,当应用程序内存不足停止抛出OutOfMemory 异常时,应该清除SoftReference 位图图像。

我在这里做错了什么?

【问题讨论】:

    标签: java listview bitmap out-of-memory


    【解决方案1】:

    我想这篇文章可能会对你有所帮助

    //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);
    
            //The new size we want to scale to
            final int REQUIRED_SIZE=70;
    
            //Find the correct scale value. It should be the power of 2.
            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;
    }
    

    【讨论】:

    • 应该是首选解决方案!
    【解决方案2】:

    OutOfMemoryError 是错误而不是异常,你不应该捕获它。

    http://mindprod.com/jgloss/exception.html

    编辑:已知问题见this issue

    【讨论】:

    • 啊,我的错……根本不知道。我能做些什么来防止它发生吗?我完全被卡住了。
    【解决方案3】:

    Error 和 Exception 是 Throwable 的子类。 错误应该非常严重,你不应该抓住它们。

    但你可以捕捉到任何东西。

    try
    { 
    }
    catch (Throwable throwable)
    {
    }
    

    【讨论】:

      猜你喜欢
      • 2012-08-19
      • 1970-01-01
      • 2010-12-29
      • 2011-07-27
      相关资源
      最近更新 更多