简体   繁体   中英

OutOfMemoryError when loading images into GridView

I am creating an app which loads images in a GridView but depending on the number of images I place in my array I get the java.lang.outofmemory error and the app crashes.
I have an ImageAdapter where the loading of the images occurs, I was following this tutorial from Androidhive . My images in total are about 4.53MB with the largest one being 1.1MB. Some images are fairly smaller. Sometimes when I load the images from my code one at a time the app runs,but when I do all images at once it crashes.

This answer seemed sensible but I could not follow with the way my project is setup. I just have a GridView and get the ImageView programatically in my code but they seem to reference from xml file.
Here is my getView() method:
@Override public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView = new ImageView(mContext); imageView.setImageResource(mThumbsIds[position]); imageView.setScaleType(ImageView.ScaleType.FIT_CENTER); imageView.setLayoutParams(new GridView.LayoutParams(200, 200)); return imageView; } @Override public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView = new ImageView(mContext); imageView.setImageResource(mThumbsIds[position]); imageView.setScaleType(ImageView.ScaleType.FIT_CENTER); imageView.setLayoutParams(new GridView.LayoutParams(200, 200)); return imageView; } where the mThumbsId is the integer array that is storing my image references from @drawable folder. I need help resizing the images with the way my project is set up and maybe the other answer can help but I cannot follow their structure.
My xml file with the gridview as well:

<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/grid_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:numColumns="auto_fit"
android:columnWidth="150dp"
android:horizontalSpacing="5dp"
android:verticalSpacing="5dp"
android:gravity="center"
android:soundEffectsEnabled="true"
android:stretchMode="columnWidth" > 

</GridView>


Thanx in advanced

The image of 1161x1161 pixels you mentioned is internally converted into a Bitmap . This Bitmap (if 32Bit) will occupy approximately 5MB (1161 x 1161 x 4 bytes) of heap memory.

Since you will have multiple of these images in memory when used in a GridView , it is no surprise you run out of memory. So yes, you should resize your images before loading them into the GridView .

Read this question/answer on how to resize : High resolution Image - OutOfMemoryError

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM