Android系统。内存不足的问题 [英] Android. OutOfMemory problems

查看:216
本文介绍了Android系统。内存不足的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在我的应用程序中显示多个图像。这些是JPG和PNG格式和我加载它们里面ImageViews像这样:

I require displaying many images in my application. These being jpgs and pngs and i'm loading them inside ImageViews like so:

tile.setImageResource(R.drawable.tile_highlight);

我目前有内存溢出的问题( java.lang.OutOfMemoryError:位图的大小超过VM预算

我已经搜索并发现了一些其他职位,他们都建议你手动回收的的ImageView的位图,就像这样:((BitmapDrawable)imageView.getDrawable())getBitmap() .recycle(); 将从内存转储

I've searched and found some other posts, they all suggest that you should recycle the bitmap of an ImageView manually, like so: ((BitmapDrawable)imageView.getDrawable()).getBitmap().recycle(); which will dump it from memory.

但对我来说,是我不是使用 setBitmap()将图像加载到ImageView的对象,当我尝试运行上述code,它返回 NullPointerException异常,更precisely,该方法 getBitmap()返回null,没有位图?!?!

BUT in my case, being that i'm not using setBitmap() to load the images onto the ImageView objects, when i try and run the above code, it returns NullPointerException, more precisely, the method getBitmap() returns null, there is no bitmap ?!?!

我需要回到我的code和改变我加载的所有图像在ImageViews的方式,然后用再循环尝试()方法?或如何可以释放内存,因此它不会再崩溃?

Do i need to go back in my code and change the way i load all the images in the ImageViews, and then try with the recycle() method? Or how can i free up the memory so it doesn't crash anymore?

修改

我已经试过像这样: imageView.setImageResource(-1); ,希望它会从内存中删除图像并把它替换...空或的东西,但现在看来,这并没有帮助的原因。

I've tried something like so: imageView.setImageResource(-1); in hopes it will remove the image from memory and replace it with ... null or something, but it seems it doesn't help the cause.

推荐答案

这将是有益的,如果你可以发布您的某些code的。具体如何你设置的ImageViews的图像。如果你不使用位图,我会期望getBitmap()将返回null。但是,如果你使用另外一种可绘制或以其他方式设置图像,有可能是类似的路线走,不涉及位图。

It would be helpful if you could post some of your code. Specifically, how you're setting the images of the ImageViews. If you're not using bitmaps, I would expect that getBitmap() will return null. However, if you're using another sort of Drawable or otherwise to set the image, there's likely a similar route to take that doesn't involve bitmaps.

编辑:

好吧,给这一个镜头。你可以从这样的资源创建位图:

Alright, give this a shot. You can create a Bitmap from a resource like this:

Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.image);

然后,使用这样的位图,考虑到IMG是您的ImageView的:

Then, use the bitmap like this, considering img is your ImageView:

img.setImageBitmap(bm);
//Do some stuff with it, then when memory gets low:
((BitmapDrawable)img.getDrawable()).getBitmap().recycle();

当然,这是考虑到你在活动中是。如果没有,你就必须获得上下文句柄,并与context.getResources替换getResources()()

Of course, this is considering that you're in an activity. If not, you'll have to get a handle on the context and replace getResources() with context.getResources().

这篇关于Android系统。内存不足的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆