Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show data from database into a RecyclerView with high performance?

I wrote my own CursorAdapter for RecyclerView like following link: https://gist.github.com/skyfishjy/443b7448f59be978bc59

Then I found whenever I change something in database and want to show it in RecyclerView, I need to create a new Cursor by db.query() and use CursorAdpater's changeCursor(). Since query() will scan all rows in database, the RecyclerView will refresh slowly when data amount is big even I insert only one row into database.

Besides, as we all know, RecyclerView provides notifyItemInserted/Removed(position) for developers so that the RecyclerView can refresh partly, which is useful and beneficial to memory/time. However, when I use CursorAdapter, I don't know when and how I can use these methods because changing cursor isn't adding something directly to dataset binding with RecyclerView but refreshing all items in fact.

So are there any better ways to show data from database in RecyclerView and use RecyclerView's improving method to show variety of database?

like image 992
ywwynm Avatar asked Sep 27 '22 20:09

ywwynm


People also ask

Can you use a RecyclerView to display data from a database?

With RecyclerView you can display a table of data, display items in a grid or if you want you can also do a Staggered layout as Pinterest does it with every item being a different size. We will show, what you need for a RecyclerView, with a small app that will show a list of cities.


1 Answers

I can tell you what i've done... A. Loaded a cursor using Loader. B. Copied the cursor into arraylist that is attached to the adapter (the cursor isnt attached to the adapter directly), close the cursor. Works well if there isnt a lot of data - if there is a lot rows then i would have load some of it to the arraylist and then when the user would scroll down i would query again and load from the last row of the array. C. When the user would like to delete or add something i would do the operation on arrayList first (UI thread) notifiyItemChanged and then change the db (Back thread) Hope i helped.

like image 190
EE66 Avatar answered Oct 13 '22 11:10

EE66