androidandroid-recyclerviewandroid-viewholdernestedrecyclerview

RecyclerView inside RecyclerView, app crashing due to high memory consumption


I wanted to create a recycler view of photo albums and when the user taps on an album, it expands to grid layout showing images in that album.

For example, non-expanded:

enter image description here

and expanded:

enter image description here

The layout of outer recyclerView item only contains a textView, checkbox, and an invisible recyclerview that becomes visible on click of the item.

I declared the outerAdapter like this:

photosVideosAdapter = new PhotosVideosAdapter(getContext(),new ArrayList<PhoneAlbum>());
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(photosVideosAdapter);

Here is the onBindViewHolder of outer adapter:

holder.tvFolder.setText(phoneAlbums.get(position).getName());
ArrayList<PhonePhoto> phonePhotos = phoneAlbums.get(position).getAlbumPhotos();
InnerAdapter innerAdapter = new InnerAdapter(context, phonePhotos);
holder.innerRecyclerView.setHasFixedSize(true);
holder.innerRecyclerView.setLayoutManager(new GridLayoutManager(context,3));
holder.innerRecyclerView.setAdapter(innerAdapter);
.... OnClickMethod to toggle visibility of innerRecyclerView

And onBindViewHolder for inner adapter:

Glide.with(context)
        .load(phonePhotos.get(position).getPhotoUri())
        .override(200,200)
        .into(holder.imgThumbnail);

The problem is that if inner recyclerView contains more than 200 items, the app crashes due to high memory usage. But as you can see, I'm using glide to load images and also RecyclerView shouldn't create all the views at once. But, what I can see is that the inner RecyclerView is creating all the item views at once which is causing the app to crash.

How can I fix this problem? Any help will be appreciated.


Solution

  • Trust me, dont go with recyclerview inside recyclerview. I had the similar situation in my current app where my colleague built solution by using nested recyclerview.

    I rewrote the entire logic using insert and delete with animation and multiple view type. It will involve some extra code to manage it. But the result would be quite satisfying.

    In fact, I used same logic in iOS collectionview as well. App on both platform is live.