Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Is it a good practice to clear Glide manually in Adapter (RecyclerView) ?

I have a Recyclerview which manages a newsfeed. There are lot of images. With Android monitor, when I scroll in this list, the memory allocated increases always ! So I added in these 2 override methods (in my Adapter):

@Override
public void onViewDetachedFromWindow(RecyclerView.ViewHolder holder) {
    super.onViewDetachedFromWindow(holder);
    clearAdapter(holder);
}

@Override
public void onViewRecycled(RecyclerView.ViewHolder holder) {
    super.onViewRecycled(holder);
    clearAdapter(holder);
}

protected void clearAdapter(RecyclerView.ViewHolder holder) {
    Glide.clear(holder.mImageView);
    ...
}

The result is better about memory allocated (but not perfect!). AND now I have a new problem, because sometimes some images are not loaded in my newsfeed (it's completely random!)

Thanks for your help guys!

like image 810
anthony Avatar asked Oct 09 '16 17:10

anthony


People also ask

How does glide work with RecyclerView?

First it collects and returns a list of Models (the items you pass in to Glide's load(Object) method, like URLs or file paths) for a given position. Second it takes a Model and produces a Glide RequestBuilder that will be used to preload the given Model into memory.

What is the use of onCreateViewHolder in Android?

This method calls onCreateViewHolder to create a new ViewHolder and initializes some private fields to be used by RecyclerView. Returns the position of the given ViewHolder in the given Adapter . Returns the total number of items in the data set held by the adapter. Return the stable ID for the item at position .

What is viewType in onCreateViewHolder?

This viewType variable is internal to the Adapter class. It's used in the onCreateViewHolder() and onBindViewHolder to inflate and populate the mapped layouts. Before we jump into the implementation of the Adapter class, let's look at the types of layouts that are defined for each view type.

What is RecyclerView in Android used for?

RecyclerView makes it easy to efficiently display large sets of data. You supply the data and define how each item looks, and the RecyclerView library dynamically creates the elements when they're needed. As the name implies, RecyclerView recycles those individual elements.


1 Answers

Calling clear in onViewRecycled should be fine. It can save memory and improve Bitmap re-use if you have a number of views in the recycled view pool (which you almost always do).

However, calling clear in onViewDetachedFromWindow is probably not fine. It's possible a view may be detached and then re-attached without being re-bound. If that happens, the view may appear empty.

Try removing the call to clearAdapter in onViewDetachedFromWindow and see if that helps.

like image 172
Sam Judd Avatar answered Sep 27 '22 18:09

Sam Judd