Recyclerview onCreateViewHolder being called despite all views being recycled? - java

Short Story:
I have a (pre-caching)Custom LinearLayoutManager, RecyclerView, Custom RecyclerView.Adaptor, Custom RecyclerView.ViewHolder setup. I have only one viewType and lightweight binding functions. Its really nothing super special which is why I hoping I don't need to post code. I also don't want to confuse with all the irrelevant code.
The issue I have is that despite not failing to recycle any views, onCreateViewHolder is still being called occasionally (after initial row inflations) leaving me wondering that maybe I have a memory leak? Do you think this is the case and why? What is deciding that my app still needs to create more views instead of recycling?
I will add one thing that maybe factoring in somehow. My rows have two visual states (they expand and collapse) and it kinda appears that having a more random mix of rows in different states worsens the problem.
Full Story:
Ive noticed an occasional hiccup in the smooth scrolling of my RecyclerView. Using android studio's profiler, I have noted the following:
All my bindViewHolder methods are plenty fast and are not holding back the scrolling.
OnCreateViewHolder is what is causing the stuttering. This explains why there is always a few stutters during the first scroll. Moreover, its the inflation thats taking a ridiculously high percentage of the cpu time.
With an item/row layout constructed using ConstraintLayout, the onMeasure functions' poor performance, destroyed the scrolling performance on weaker devices.
With an item/row layout constructed using LinearLayouts, the performance improved drastically. However, the inflation of views still takes long enough to cause hickups.
With this information, I have simplified my row item's layout as much as possible making sure to use LinearLayouts. Irregardless, the rendering of the recyclerview's items shouldnt result in stuttering after the first items come on screen because one, the rows are all the same except for the data binded to them and two, the RecyclerView is supposed to recycle the rows. So onCreateViewHolder should be called a lot initially and then rarely called again. What about pre-caching? I have found this to be one reason that new viewholders are requested when scrolling. I set the cache and created a custom LinearLayoutManager that overrides the pre-caching (pre-fetching?) method called getExtraLayoutSpace(RecyclerView.State state) and adjusted the two so that there are enough existing recyclable views to cover the request during scroll. My tests confirm that after initial scroll, new views arent requested when transitioning into scrolling state.
All that and I have two issues remaining. One of them being that onCreateViewHolder is called every so often during the use of the app and this causes a little hiccup. I put a Log.w() inside onFailedToRecycleView() to see any views are not being recycled and it looks like views are being recycled. So now I think there is some memory leak and the memory profiler shows jumps in memory usage often occuring when onCreateViewHolder is called.

The three questions I posted where,
Do I have a memory leak because Recyclerview keeps creating Viewholders?
Why do I have a memory leak?
What is deciding that my app still needs to create more views instead of recycling?
I believe I have essentially found the solution to the 2 out of 3 of the questions or the respective underlying problems.
Inside Recyclerview class is a Recycler class and RecycledViewPool class. The internal Recycler object is what makes a request to the RecycledViewPool object for an available detached scrap viewholder to recycle if it doesnt already have an attached scrap viewholder to recycle. And specifically, this search for a recyclable viewholder happens inside Recycler's getViewForPosition(int position) function. If (inside this function), a recyclable view is not found, then mAdapter.createViewHolder(RecyclerView.this, type) is called. This leads to onCreateViewholder being called. So to answer the 3rd question, Recycler is deciding when to call onCreateViewholder.
Note that the RecycledViewPool's job is to maintain an array of arraylists of detached scrap viewholders (1d array of an arraylist of each viewType). The maintaining functions include clear() , reset(), and setMaxScrap(int viewType, int max) which do what their names indicate. So the pathway to the solution to second question is to create a custom RecycledViewPool that indicates when scraplist is cleared or diminished so I can track the creation and destruction of scrap views. As far as question 1, this can be solved by using setMaxScrap(int viewType, int max). Also, on initialization of the recyclerview we can put a few extra scrapviews in the pool and try to maintain a minimum number of scrapviews which can probably be done with a listener.

Related

One large scrolling list of different items -> Better solution than RecyclerView?

I was prototyping an app with a recycler view where it boiled down to basically this concept:
There is one single list, which is entirely scrollable (this bit is important).
The items in question in the recycler view are however very heterogeneous. It is not like I want to have either an image or a text, but sometimes it is a simple "list item (clickable text)", sometimes it is a row with 3 buttons, sometimes it is an icon with text, another one is a button, etc.
While similar item types have similar behaviour, the groups itself are different. They need a different manager, a different ViewHolder to process their very different button events etc.
I find it not very convenient to put everything into the recycler view's adapter with some common base class and delegate everything those different items can do to some callbacks. It feels very clunky.
Is there some better way of handling that? The advantage of the recycler view is that it scrolls well. I personally do not need any lazy creation of those items (= recycling) so I am not winning much here. The other advantage is that I do not need to handle every items creation. Which is also the downside, I need to channel it through the adapter with its getItemViewType based on position etc.

RecyclerView with unknown/variable row layouts

Since RecyclerView uses ViewHolders, it means that you must have a predefined layout for each row. But what if each row needs to have a variable amount of views displayed?
For example, say I'm creating an instant messaging application where users can attach pictures to messages. They could attach anywhere from 0 to x pictures. When you create a RecyclerView to display these pictures (that are downloaded from a server), how would you make the rows include the correct number of ImageViews to display them?
There's a few ways I can think of doing this, but none really seem like good options.
Create ImageViews in onBindViewHolder, add them to a layout in the ViewHolder. (Isn't this what the ViewHolder tries to prevent? This would probably be laggy, especially with lots of pictures)
Restrict the amount of pictures the user can attach to a message to x, then add x ImageViews to the layout that are set to invisible/gone. In onBindViewHolder, set the ImageViews to display the picture and set these ImageViews visible. (What if I allow pictures & videos to be attached? Do I then need to add x ImageViews and x VideoViews as well?)
Put a GridView in each RecyclerView item and populate the GridView
inside onBindViewHolder. (I assume this would have no benefit over
option #1 because it's pretty much the same thing?)
That's all I can think of. Is there any other option that is designed for this sort of situation that I have not come across? Or what are the typical approaches taken towards this problem?
You need to create a heterogenous RecyclerView which will display multiple different ViewHolders. There are several ways to accomplish this.
The basic approach is that based on the number of photos/videos associated with each item in your RecyclerView.Adapter you would override getItemViewType(int position) (a method which is part of the RecyclerView.Adapter class) to return a different int. This int is the viewType parameter passed into createViewHolder(ViewGroup parent, int viewType). You would then use the correct ViewHolder/layout based on the viewType argument.
See here for a good tutorial.
If you don't mind using a library for an alternate approach I recommend AdapterDelegates.

Android Recyclerview for a few items

I have a list CardViews, each of which has a title and an icon. Upon clicking on each item, an Activity opens with that certain card's details.
I don't think I need more than a few items (I don't think more than 10), and I'm not sure how dynamic and changing they will be.
My question is: Should I use a RecyclerView to show these items, or should I just duplicate the cards and show them inside a LinearLayout without a RecyclerView?
In terms of performance, which option is better?
Both options should be OK (I haven't tested the performance, but both run OK), although I would prefer the Linearlayout. Because the list is small, you lose most advantages of the RecyclerView (performance-wise).
If you decide to go with the LinearLayout, you could create a Compound control and reuse it for the different items so you don't have to edit every item manually if something changes.
And if you would decide to use the RecyclerView, don't forget to call setItemViewCacheSize() and set it to a reasonable amount (the count of your items), because for so few items it doesn't make sense to need to re-populate the items every time you scroll. It makes sense for bigger lists, where you can't effectively work with that many items, but for cca 10 items it seems faster if you cache them all. The next thing you should also do is call setHasFixedSize(true) on the RecyclerView. And if you don't need nested scrolling, call setNestedScrollingEnabled(false) too, otherwise the scrolling might behave a bit strange (no "fast/continued scrolling" if you swipe quickly).
Hope this helps.

When onBindViewHolder is called and how it works?

I am a beginner and I am having trouble with understanding a piece of code. Can someone please explain me when this function evoke and what is it for?
Here is my code :
public void onBindViewHolder(myViewHolder holder, int position) {
RecViewHolder currentdata = data.get(position);
holder.favChecker = currentdata.getFavChecker();
holder.serialID = currentdata.getSerialID();
holder.theClassName = currentdata.getTheClassName();
}
Let me start with just a little bit of background (which you may already understand, but it's needed to explain onBindViewHolder()).
RecyclerView is designed to display long lists (or grids) of items. Say you want to display 100 rows of something. A simple approach would be to just create 100 views, one for each row and lay all of them out. But that would be wasteful, because most of them would be off screen, because lets say only 10 of them fit on screen.
So RecyclerView instead creates only the 10 views that are on screen. This way you get 10x better speed and memory usage. But what happens when you start scrolling and need to start showing next views?
Again a simple approach would be to create a new view for each new row that you need to show. But this way by the time you reach the end of the list you will have created 100 views and your memory usage would be the same as in the first approach. And creating views takes time, so your scrolling most probably wouldn't be smooth.
This is why RecyclerView takes advantage of the fact that as you scroll and new rows come on screen also old rows disappear off screen. Instead of creating new view for each new row, an old view is recycled and reused by binding new data to it.
This happens exactly in onBindViewHolder(). Initially you will get new unused view holders and you have to fill them with data you want to display. But as you scroll you'll start getting view holders that were used for rows that went off screen and you have to replace old data that they held with new data.
It is called by RecyclerView to display the data at the specified position. This method is used to update the contents of the itemView to reflect the item at the given position.
for more info check RecyclerView.Adapter#onBindViewHolder

android listview with real-time sensor updates

I am working on a app that shows some places in a listview. In every listview item there is a arrow pointing towards the place(hotel, bar etc).
The problem is I don't know how to keep this arrow updated efficiently, without cashing views locally( which, according to a Google I/O video, is something i should never ever do).
The arrow needs to be updated on every phone orientation sensor event, which is many times a second.
So is there a better approach than calling notifyDataSetChanged() on every event and refiling every list item data?
UPDATE (for #dharan and anyone interested):
I have stopped working on this project because I have a full-time job now, but I thought of a solution (unimplemented/untested).
First limit the angle of rotation to a fixed step, (eg: 5, 10, 15, 20, ... 355, 360) then cache the rotated image for each angle of rotation in order to avoid expensive image rotation calculations (but at a higher memory cost).
After that I would make my getView() method know when to only update the image instead of all the data. In my case this is as easy as:
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView != null && place[position].id == (Integer)convertView.getTag()){
//the place information is already set correctly so just update the image
}
...
}
After these modifications I believe that calling notifyDataSetChanged() should not cause serious performance issues.
If you don't have too many items in the ListView you could convert to using a plain LinearLayout and control those items individually. The problem with LinearLayout though is if an item changes its size then everything (ie all children) has to be relayed out. So triggering a change in one item can re-trigger other things to layout as well. Now because you're changing a compass needle you might be able to skirt around it because that shouldn't cause each row to change its overall size. You just need to repaint that item.
The other option is to write your own layout that takes some short cuts making some assumptions the general purpose layout managers can't. The last thing I might look at is what does notifyDataSetChanged() does under the covers. You might be able to extend ListView and write a method that only redraws the row that changed (of course this assumes the height of the row hasn't changed). If the row height changes then everything after that row has to be relayed out.

Categories

Resources