Android Out of Memory Error when loading images fr

2019-07-12 19:31发布

问题:

I have a layout which I'm adding ImageViews (about 13) to at run time using a single thread. When I load more than 7 or 8 images (970px x 970px, 270kb) the application crashes displaying an out of memory error. Now when I load the same image rather than choosing 13 different images it displays fine. And also when I reduce the size of the images (16px x 16px, 770bytes) it displays fine.

So does anyone know what the max memory allowed when loading images? What is the best way to get around this issue? Obviously people have come across this issue before and solved it due to loading image galleries etc.. what's the best way to load these images into the application? Any help would be greatly appreciated.

The following is how I'm reading the image from the resources. This is within a loop that I am taking the "drawableName" from a list of objects that I'm reading through. This is all within the onPostExecute of a thread (i.e. new AsyncTask())

String defType = "drawable";
String defPackage = this.getPackageName();
int resourceId = Activity.this.getResources().getIdentifier(drawableName, defType, defPackage);
((ImageView) view.findViewById(R.id.iv_image)).setImageResource(resourceId);

回答1:

The fastest way to resolve your problem is to use the Picasso library from Jake Wharton. It enables in one line of code to load your image and manage caching, transformations, download etc..

Here is the link to download the library: http://square.github.io/picasso/

All the code you need is :

Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);

It should work like a charm :)



回答2:

I would try by loading only the images that are going to be shown and resizing them to an appropiate size. There are guides in the android docs about displaying images efficiently read here

You can also checkout Picasso library http://square.github.io/picasso/ wich I find very useful for these kinds of tasks.