A generic way of backing an Android RecyclerView with a Firebase location.
- It handles all of the child events at the given Firebase location.
- It marshals received data into the given class type.
- Simplifies the management of configuration change (e.g.: device rotation) allowing the restoring of the list.
No modules, just copy FirebaseRecyclerAdapter in your project and extend it.
Create an adapter class extending FirebaseRecyclerAdapter and exposing a Viewholder and the Model of the Firebase childs:
public class MyAdapter extends FirebaseRecyclerAdapter<MyAdapter.ViewHolder, MyItem>
(example here).
FirebaseRecyclerAdapter constructor takes two parameters:
query
: The Firebase location to watch for data changesitemClass
: The class of the items (childs)
FirebaseRecyclerAdapter will handle the item list (listening from a Firebase location) and you can handle the view logic in your new adapter where you must:
- Declare a constructor that calls
super(params...)
with the default FirebaseRecyclerAdapter constructor parameters. - Override
onCreateViewHolder
andonBindViewHolder
and handle your viewholder logic here like a classic adapter (inonBindViewHolder
you can get the item with thegetItem(int position)
method of FirebaseRecyclerAdapter, e.g.:MyItem item = getItem(position)
. - Implement the abstract methods
itemAdded
,itemChanged
,itemRemoved
,itemMoved
that will notify you when the list changes.
Create your adapter just like you always do and pass the interested parameter to its constructor:
mMyAdapter = new MyAdapter(mQuery, MyItem.class);
You're done!
Remember to call
MyAdapter.destroy
before destroying the adapter to remove the Firebase location listener!
If you're interested in device rotation handling you should:
- Save FirebaseRecyclerAdapter
mItems
andmKeys
before destroying the adapter: just put them in a onSavedInstance Bundle (be careful, your must declare the item/child class model asParcelable
). You can get them withgetItems()
andgetKeys()
. - Call
MyAdapter.destroy
before destroying the adapter. - Re-create the adapter (after the device rotation) passing the saved
mItems
andmKeys
to the second constructor:mMyAdapter = new MyAdapter(mQuery, MyItem.class, mAdapterItems, mAdapterKeys);
.
Here is a working example where I handled device rotation (I used Parceler to make myItem parcelable).
Thanks to FirebaseListAdapter for the starting idea.