baekacaek
baekacaek

Reputation: 1557

Out of memory error when nesting gridview inside listview

I'm trying to add a GridView of images (ImageView) for my android application. I've successfully implemented lazy loading and caching of images and all of my high quality images work flawlessly when I have a simple GridView. However, the problem occurs when I try to nest my GridView inside a ListView.

When I simply have a GridView, the app only has to keep reference to images that are currently being rendered on the screen. But when I nest a GridView of, say 100 hi-res images, inside a ListView, the app tries to keep a reference to all 100 images, when only 20 of them are being rendered on the screen at the time. I found this out through my Log output, where the app would print a message every time an image is "read". I would see the app read 20 images that are being displayed on the screen, but then it would keep going and read more images. When it reaches around 100~ images, the app would run out of memory and crash. This behavior does not happen when I have just the GridView; the app will just read 20 images, and load more as I scroll the screen.

How can I make it so that my ListView does not try to load all elements inside a child view (especially the one that's not being displayed on screen)?

Thanks!

EDIT: For those wondering why I would want a GridView inside a ListView, it's because I'm trying to create something like this: nested GridView

Except I'd like to have it in a ListView, as opposed to ExpandableListView.

Upvotes: 0

Views: 1072

Answers (2)

elegant
elegant

Reputation: 33

You are getting this Exception because in an expanded GridView all the data is loaded in memory, if your data is too much it will cause OutOfMemory Exception.
The solution is: divide your data in small parts and then try.

Upvotes: 2

Oscar Salguero
Oscar Salguero

Reputation: 10365

You can not nest scrollable Views in Android. Components such as ListView, GridView, ScrollView can't be nested into each other.

You should take a look at Fragments (http://developer.android.com/guide/components/fragments.html) and stop to re-think your UI a little bit.

And... for large datasets, image/data lazy-loading is not enough... it is highly recommended that you implement a paging mechanism that would allow the user to page trough the results/content.

Let's say you'll display 20 items at a time. You will have to add a Next and a Previous buttons on the sides of the GridView UI (or you can do it the cool way with gestures)... and tweak your GridView's Adapter logic to pull only 20 items from your Model or from the Server at a time.

I found a really simple implementation of paging with a grid view among my bookmarks: http://paulononaka.wordpress.com/2011/03/19/how-to-implement-a-paging-feature-in-android/ ... I bet there are better ways to do it, but it could give you ideas.

Good luck!

Upvotes: 0

Related Questions