Error inflating class when trying to decodeStream

て烟熏妆下的殇ゞ 提交于 2019-12-02 09:59:54

Where you have the warning 'The value of the local variable bmp is not used' in decodeAndResizeFile(), you can remove the 'Bitmap bmp =' part and leave it as:

BitmapFactory.decodeResource(context.getResources(), resID, o);

This is because this call is with o.inJustDecodeBounds = true. When that is the case, only the dimensions are returned in object 'o' and a null bitmap is returned (so there's no point storing it).

In your switch statement, change each case to be like the following:

case R.id.WPimg1:
    toPhone = R.drawable.wal1;
    bmpp = decodeAndResizeFile(toPhone);
    display.setImageBitmap(bmpp);
    break;

So here, you decode the resource into a scaled down bitmap and then assign that bitmap to the ImageView. You don't want or need to do this:

display.setImageResource(R.drawable.wal1);

...since you're risking an OutOfMemoryException and you go on to set 'display' with the scaled bitmap anyway. Having made those changes, your code works for me. I can see the wallpaper preview images and then set the wallpaper (don't forget the SET_WALLPAPER permission in the manifest).

That doesn't however explain your logcat which appears to be a problem in onCreate() inflating R.layout.activity_main. Towards the end of your logcat, it shows an OutOfMemoryError again. I can re-create this error if I assign a large jpg to an ImageView in the XML (an OOM results and the layout therefore cannot be inflated). You cannot scale down drawables 'on-the-fly' when they are assigned in XML, so create physically smaller drawables for use within the XML.

EDIT:

When you click on an image, 'display' gets a new bitmap and the old one is eligible for GC. Here is one approach for releasing the memory used by the old one right away, without waiting for GC to kick in:

Move this from onClick() to being a class variable instead:

Bitmap bmpp;  //Reference to the same bitmap that 'display' is using

Then in onClick():

Bitmap old_bm = null;  //Reference to hold the old bitmap
switch (v.getId()){
case R.id.WPimg1:
    old_bm = bmpp;  //Set to the bitmap currently being used by 'display'
    toPhone = R.drawable.wal1;
    bmpp = decodeAndResizeFile(toPhone);   //'display' now has a new bitmap
    display.setImageBitmap(bmpp);
    if (old_bm != null)
    {
        old_bm.recycle();  //Recyle the old bitmap
        old_bm = null;     //Clear the reference to allow GC to clean up fully
    }
    break;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!