【问题标题】:Android application crashes when showing multiple images in GridView component在 GridView 组件中显示多个图像时,Android 应用程序崩溃
【发布时间】:2013-06-28 17:10:47
【问题描述】:

我对这个网站相当陌生,我在这里是因为我在其他任何地方都找不到这个答案,所以我想看看我是否能得到一些帮助!

我的项目中有一个 GridView 以及一个图像适配器。我需要以下代码的帮助:

package com.humanoid.sigma;

import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

public class ImageAdapter extends BaseAdapter {
private Context mContext;


public Integer[] Tattoos = {
        R.drawable.tattoo1, R.drawable.tattoo2,
        R.drawable.tattoo3, R.drawable.tattoo4,
        R.drawable.tattoo5, /*R.drawable.tattoo6,
        R.drawable.tattoo7, R.drawable.tattoo8,
        R.drawable.tattoo9, R.drawable.tattoo10, 
        R.drawable.tattoo11, R.drawable.tattoo12,
        R.drawable.tattoo13, R.drawable.tattoo14,
        R.drawable.tattoo15, R.drawable.tattoo16,
        R.drawable.tattoo17, R.drawable.tattoo18,
        R.drawable.tattoo19, R.drawable.tattoo20, 
        R.drawable.tattoo21, R.drawable.tattoo22,
        R.drawable.tattoo23, R.drawable.tattoo24,
        R.drawable.tattoo25, R.drawable.tattoo26,
        R.drawable.tattoo27, R.drawable.tattoo28,
        R.drawable.tattoo29, R.drawable.tattoo30, 
        R.drawable.tattoo31, R.drawable.tattoo32,
        R.drawable.tattoo33, R.drawable.tattoo34,
        R.drawable.tattoo35, R.drawable.tattoo36,
        R.drawable.tattoo37, R.drawable.tattoo38,
        R.drawable.tattoo39, R.drawable.tattoo40, 
        R.drawable.tattoo41, R.drawable.tattoo42,
        R.drawable.tattoo43, R.drawable.tattoo44,
        R.drawable.tattoo45, R.drawable.tattoo46,
        R.drawable.tattoo47, R.drawable.tattoo48,
        R.drawable.tattoo49, R.drawable.tattoo50, 
        R.drawable.tattoo51, R.drawable.tattoo52,
        R.drawable.tattoo53, R.drawable.tattoo54,
        R.drawable.tattoo55, R.drawable.tattoo56,
        R.drawable.tattoo57, R.drawable.tattoo58,
        R.drawable.tattoo59, R.drawable.tattoo60, 
        R.drawable.tattoo61, R.drawable.tattoo62,
        R.drawable.tattoo63, R.drawable.tattoo64,
        R.drawable.tattoo65, R.drawable.tattoo66,
        R.drawable.tattoo67, R.drawable.tattoo68,
        R.drawable.tattoo69, R.drawable.tattoo70, 
        R.drawable.tattoo71, R.drawable.tattoo72,
        R.drawable.tattoo73, R.drawable.tattoo74,
        R.drawable.tattoo75, R.drawable.tattoo76,
        R.drawable.tattoo77, R.drawable.tattoo78,
        R.drawable.tattoo79, R.drawable.tattoo80,
        R.drawable.tattoo81, R.drawable.tattoo82,*/

};

// Constructor
public ImageAdapter(Context c){
    mContext = c;
}

public int getCount() {
    return Tattoos.length;
}

public Object getItem(int position) {
    return Tattoos[position];
}

public long getItemId(int position) {
    return 0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ImageView imageView = new ImageView(mContext);
    imageView.setImageResource(Tattoos[position]);
    imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
    imageView.setLayoutParams(new GridView.LayoutParams(100, 70));
    return imageView;
}

}

Logcat 堆栈跟踪:

06-28 17:51:14.104:E/AndroidRuntime(818):致命异常:主要 06-28 17:51:14.104: E/AndroidRuntime(818):
java.lang.OutOfMemoryError 06-28 17:51:14.104: E/AndroidRuntime(818): 在
android.graphics.BitmapFactory.nativeDecodeAsset(Native Method) 06-28 17:51:14.104:E/AndroidRuntime(818):在 android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:502) 06-28 17:51:14.104: E/AndroidRuntime(818): 在 android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:355) 06-28 17:51:14.104: E/AndroidRuntime(818): 在 android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:785) 06-28 17:51:14.104: E/AndroidRuntime(818): 在 android.content.res.Resources.loadDrawable(Resources.java:1965) 06-28 17:51:14.104:E/AndroidRuntime(818):在 android.content.res.Resources.getDrawable(Resources.java:660) 06-28 17:51:14.104:E/AndroidRuntime(818):在 android.widget.ImageView.resolveUri(ImageView.java:616) 06-28 17:51:14.104:E/AndroidRuntime(818):在 android.widget.ImageView.setImageResource(ImageView.java:349) 06-28 17:51:14.104:E/AndroidRuntime(818):在 com.humanoid.sigma.ImageAdapter.getView(ImageAdapter.java:80) 06-28 17:51:14.104:E/AndroidRuntime(818):在 android.widget.AbsListView.obtainView(AbsListView.java:2143) 06-28 17:51:14.104:E/AndroidRuntime(818):在 android.widget.GridView.makeAndAddView(GridView.java:1341) 06-28 17:51:14.104:E/AndroidRuntime(818):在 android.widget.GridView.makeRow(GridView.java:341) 06-28 17:51:14.104: E/AndroidRuntime(818):在 android.widget.GridView.fillDown(GridView.java:283) 06-28 17:51:14.104:E/AndroidRuntime(818):在 android.widget.GridView.fillFromTop(GridView.java:417) 06-28 17:51:14.104:E/AndroidRuntime(818):在 android.widget.GridView.layoutChildren(GridView.java:1229) 06-28 17:51:14.104:E/AndroidRuntime(818):在 android.widget.AbsListView.onLayout(AbsListView.java:1994) 06-28 17:51:14.104:E/AndroidRuntime(818):在 android.view.View.layout(View.java:14003) 06-28 17:51:14.104: E/AndroidRuntime(818):在 android.view.ViewGroup.layout(ViewGroup.java:4375) 06-28 17:51:14.104: E/AndroidRuntime(818):在 android.widget.RelativeLayout.onLayout(RelativeLayout.java:985) 06-28 17:51:14.104:E/AndroidRuntime(818):在 android.view.View.layout(View.java:14003) 06-28 17:51:14.104: E/AndroidRuntime(818):在 android.view.ViewGroup.layout(ViewGroup.java:4375) 06-28 17:51:14.104: E/AndroidRuntime(818):在 android.widget.FrameLayout.onLayout(FrameLayout.java:448) 06-28 17:51:14.104:E/AndroidRuntime(818):在 android.view.View.layout(View.java:14003) 06-28 17:51:14.104: E/AndroidRuntime(818):在 android.view.ViewGroup.layout(ViewGroup.java:4375) 06-28 17:51:14.104: E/AndroidRuntime(818):在 android.widget.LinearLayout.setChildFrame(LinearLayout.java:1663) 06-28 17:51:14.104: E/AndroidRuntime(818): 在 android.widget.LinearLayout.layoutVertical(LinearLayout.java:1521) 06-28 17:51:14.104: E/AndroidRuntime(818): 在 android.widget.LinearLayout.onLayout(LinearLayout.java:1434) 06-28 17:51:14.104:E/AndroidRuntime(818):在 android.view.View.layout(View.java:14003) 06-28 17:51:14.104: E/AndroidRuntime(818):在 android.view.ViewGroup.layout(ViewGroup.java:4375) 06-28 17:51:14.104: E/AndroidRuntime(818):在 android.widget.FrameLayout.onLayout(FrameLayout.java:448) 06-28 17:51:14.104:E/AndroidRuntime(818):在 android.view.View.layout(View.java:14003) 06-28 17:51:14.104: E/AndroidRuntime(818):在 android.view.ViewGroup.layout(ViewGroup.java:4375) 06-28 17:51:14.104: E/AndroidRuntime(818):在 android.view.ViewRootImpl.performLayout(ViewRootImpl.java:1892) 06-28 17:51:14.104:E/AndroidRuntime(818):在 android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1711) 06-28 17:51:14.104: E/AndroidRuntime(818): 在 android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:989) 06-28 17:51:14.104:E/AndroidRuntime(818):在 android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4351) 06-28 17:51:14.104: E/AndroidRuntime(818): 在 android.view.Choreographer$CallbackRecord.run(Choreographer.java:749) 06-28 17:51:14.104: E/AndroidRuntime(818): 在 android.view.Choreographer.doCallbacks(Choreographer.java:562) 06-28 17:51:14.104:E/AndroidRuntime(818):在 android.view.Choreographer.doFrame(Choreographer.java:532) 06-28 17:51:14.104:E/AndroidRuntime(818):在 android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735) 06-28 17:51:14.104: E/AndroidRuntime(818): 在 android.os.Handler.handleCallback(Handler.java:725) 06-28 17:51:14.104:E/AndroidRuntime(818):在 android.os.Handler.dispatchMessage(Handler.java:92) 06-28 17:51:14.104:E/AndroidRuntime(818):在 android.os.Looper.loop(Looper.java:137) 06-28 17:51:14.104: E/AndroidRuntime(818):在 android.app.ActivityThread.main(ActivityThread.java:5039) 06-28 17:51:14.104:E/AndroidRuntime(818):在 java.lang.reflect.Method.invokeNative(Native Method) 06-28 17:51:14.104:E/AndroidRuntime(818):在 java.lang.reflect.Method.invoke(Method.java:511) 06-28 17:51:14.104: E/AndroidRuntime(818):在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 06-28 17:51:14.104: E/AndroidRuntime(818): 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 06-28 17:51:14.104:E/AndroidRuntime(818):在 dalvik.system.NativeStart.main(Native Method)

Gallery.Java 代码:

package com.humanoid.sigma;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

public class Gallery extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.gallery);

    GridView gridView = (GridView) findViewById(R.id.photos);

    // Instance of ImageAdapter Class
    gridView.setAdapter(new ImageAdapter(this));
    gridView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View v,
                int position, long id) {

            // Sending image id to FullScreenActivity
            Intent i = new Intent(getApplicationContext(), FullScreen.class);
            // passing array index
            i.putExtra("id", position);
            startActivity(i);
        }
    });
}
}

正如您从上面看到的,我已经注释掉了对我不起作用的内容。我不知道是不是因为这个 GridView 的图片太多,但它很烦人。一旦我将这些图像注释掉,程序运行良好,但如果我删除 /* 并运行程序并选择图库,它只会显示黑屏。不久之后它就会崩溃。

请帮我处理这段代码,我一直在搜索,但找不到任何帮助。

【问题讨论】:

  • 给我们 logcat 堆栈跟踪
  • 好的,我已经编辑了上面的帖子,以便查看 Logcat 堆栈跟踪。
  • 对它的外观感到抱歉。不幸的是,我无法让它看起来整洁。
  • 我在你的堆栈跟踪中找不到任何有用的东西
  • 看这里getView方法:stackoverflow.com/q/3614779/1276374

标签: java android memory-leaks android-gridview


【解决方案1】:

您的问题是由于在分配可绘制资源时堆大小耗尽(这是一个常见问题,因为这种操作需要大量内存)。

当我尝试了您的代码时,我得到了 java.lang.OutOfMemoryError: bitmap size exceeds VM budget 。这是一个简单的不言自明的错误消息。

然后我做了一些研究,并在官方 Android 开发网站上发现了一个“原生”线程:http://developer.android.com/training/displaying-bitmaps/index.html 关于位图和如何在应用程序中进行有效资源分配的示例。

所以我尝试了它并结合你的代码,这就是我得到的:

ImageAdapter.java

package com.humanoid.sigma;

import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

public class ImageAdapter extends BaseAdapter {
private Context mContext;


public Integer[] Tattoos = {
        R.drawable.tattoo1, R.drawable.tattoo2,
        R.drawable.tattoo3, R.drawable.tattoo4,
        R.drawable.tattoo5, R.drawable.tattoo6,
        R.drawable.tattoo7, R.drawable.tattoo8,
        R.drawable.tattoo9, R.drawable.tattoo10, 
        R.drawable.tattoo11, R.drawable.tattoo12,
        R.drawable.tattoo13, R.drawable.tattoo14,
        R.drawable.tattoo15, R.drawable.tattoo16,
        R.drawable.tattoo17, R.drawable.tattoo18,
        R.drawable.tattoo19, R.drawable.tattoo20, 
        R.drawable.tattoo21, R.drawable.tattoo22,
        R.drawable.tattoo23, R.drawable.tattoo24,
        R.drawable.tattoo25, R.drawable.tattoo26,
        R.drawable.tattoo27, R.drawable.tattoo28,
        R.drawable.tattoo29, R.drawable.tattoo30, 
        R.drawable.tattoo31, R.drawable.tattoo32,
        R.drawable.tattoo33, R.drawable.tattoo34,
        R.drawable.tattoo35, R.drawable.tattoo36,
        R.drawable.tattoo37, R.drawable.tattoo38,
        R.drawable.tattoo39, R.drawable.tattoo40, 
        R.drawable.tattoo41, R.drawable.tattoo42,
        R.drawable.tattoo43, R.drawable.tattoo44,
        R.drawable.tattoo45, R.drawable.tattoo46,
        R.drawable.tattoo47, R.drawable.tattoo48,
        R.drawable.tattoo49, R.drawable.tattoo50, 
        R.drawable.tattoo51, R.drawable.tattoo52,
        R.drawable.tattoo53, R.drawable.tattoo54,
        R.drawable.tattoo55, R.drawable.tattoo56,
        R.drawable.tattoo57, R.drawable.tattoo58,
        R.drawable.tattoo59, R.drawable.tattoo60, 
        R.drawable.tattoo61, R.drawable.tattoo62,
        R.drawable.tattoo63, R.drawable.tattoo64,
        R.drawable.tattoo65, R.drawable.tattoo66,
        R.drawable.tattoo67, R.drawable.tattoo68,
        R.drawable.tattoo69, R.drawable.tattoo70, 
        R.drawable.tattoo71, R.drawable.tattoo72,
        R.drawable.tattoo73, R.drawable.tattoo74,
        R.drawable.tattoo75, R.drawable.tattoo76,
        R.drawable.tattoo77, R.drawable.tattoo78,
        R.drawable.tattoo79, R.drawable.tattoo80,
        R.drawable.tattoo81, R.drawable.tattoo82

};

// Constructor
public ImageAdapter(Context c){
    mContext = c;
}

public int getCount() {
    return Tattoos.length;
}

public Object getItem(int position) {
    return Tattoos[position];
}

public long getItemId(int position) {
    return 0;
}

public View getView(int position, View convertView, ViewGroup parent) {
    //This actually is a bad solution, because every time convertView is reused, you will still initialize new ImageView, which is wrong
    //ImageView imageView = new ImageView(this.mContext);
    //new BitmapWorkerTask(imageView).execute(Tattoos[position]);
    //return imageView;

    //Better solution
    ImageView imageView = null;

    if (convertView == null) {
        imageView = new ImageView(this.mContext);
        new BitmapWorkerTask(imageView).execute(Tattoos[position]);
        //create new ImageView if it is not present and populate it with some image
    } else {
        imageView = (ImageView) convertView;
        //re-use ImageView that already exists in memory
    }

return imageView;
}


class BitmapWorkerTask extends AsyncTask<Integer, Void, Bitmap> {
        private final WeakReference<ImageView> imageViewReference;
        private int data = 0;

        public BitmapWorkerTask(ImageView imageView) {
            // Use a WeakReference to ensure the ImageView can be garbage collected
            imageViewReference = new WeakReference<ImageView>(imageView);
        }

        // Decode image in background.
        @Override
        protected Bitmap doInBackground(Integer... params) {
            data = params[0];
            return decodeSampledBitmapFromResource(ImageAdapter.this.mContext.getResources(), data, 100, 100);
        }

        // Once complete, see if ImageView is still around and set bitmap.
        @Override
        protected void onPostExecute(Bitmap bitmap) {
            if (imageViewReference != null && bitmap != null) {
                final ImageView imageView = imageViewReference.get();
                if (imageView != null) {
                    imageView.setImageBitmap(bitmap);
                    imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                    imageView.setLayoutParams(new GridView.LayoutParams(100, 70));
                }
            }
        }
    }

    public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
                                                         int reqWidth, int reqHeight) {

        // First decode with inJustDecodeBounds=true to check dimensions
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(res, resId, options);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeResource(res, resId, options);
    }

    public static int calculateInSampleSize(
            BitmapFactory.Options options, int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {

            // Calculate ratios of height and width to requested height and width
            final int heightRatio = Math.round((float) height / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);

            // Choose the smallest ratio as inSampleSize value, this will guarantee
            // a final image with both dimensions larger than or equal to the
            // requested height and width.
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }

        return inSampleSize;
    }

}

它异步加载图像并对加载的资源做了一些额外的魔法。

这个解决方案对我来说很好,当你运行你的代码时,你实际上可以看到一次加载一个图像,从一个重量较轻的图像开始向上,我猜,因为对于每个ImageView将是一个单独的工作人员Thread,它将加载和转换资源,然后将其应用到ImageView

证明:

【讨论】:

  • 我喜欢您设置代码的方式,但如何将其实现到我的代码中?抱歉,我对 Android 的整个开发还很陌生。
  • @Kodi 我编辑了我的答案,只需将您在上面看到的所有代码复制到您的类实现中。希望这会有所帮助
  • 刚试了一下,还是不行。我放了一张我应该将上下文更改为的屏幕截图。它给了我三个选项,但我尝试了“在“ImageAdapter”类型中创建字段“上下文”和“更改为 mContext”。第一个只是让画廊崩溃,不让我打开另一个 xml 布局,而后来让我打开画廊,但是一旦我继续使用 xml 布局,它就黑屏了几秒钟,然后它就崩溃了。也许我做错了什么?
  • 显然我无法添加照片或为您的帖子点赞 -_- 但另一个选项是“在“ImageAdapter”类型中创建常量“上下文”
  • @Kodi 是的,你做错了什么。而且我的回答也做错了,因为我自己的代码只是重用了你的某些部分,所以我使用了自己的变量名..随便。所以为了让它工作 - 将context变量名更改为mContext。因为它是您想要保留的主要活动的上下文。我编辑了我的答案
猜你喜欢
  • 1970-01-01
  • 2014-05-04
  • 1970-01-01
  • 1970-01-01
  • 2019-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多