It is unclear how to manage object keys in ListView / RecyclerView
See original GitHub issuePossible doc enhancement?
Background
I came across this when trying to create a RecyclerView that launches a fragment with details about a list item when that list item is tapped. This would involve passing the key of the list item object to the details fragment so that details can be loaded. (Example: App shows a list of messages, user taps on a message and sees a new screen that shows details about the message)
Problem
There is no recommended pattern for tracking an object’s key in a FirebaseListAdapter
/FirebaseRecyclerAdapter
in the firebase-ui-database docs, which is the place I would go to learn how to use a RecyclerView with FirebaseUI.
This StackOverflow answer presents a way to retrieve the key of an object inside FirebaseListAdapter by adapter.getRef(position).getKey()
but says that this method should be used as a last resort.
The docs for creating a model class show a field inside the model class, there called mUid
, used to track a unique identifier. However, in this example the uid
is different from the key of the object in the Firebase db. This means that querying is not a simple path like mDatabase.child("messages").child(key)
, but would instead have to be something like mDatabase.child("messages").orderByChild("uid").equalTo(mUid)
.
One solution might be to use mDatabase.child("posts").push().getKey()
as the uid
when the object is created, so that the uid
matches the actual key in the db, and querying the object as a path like mDatabase.child("messages").child(key)
is possible.
The other option I can see is to always use adapter.getRef(position).getKey()
, to prevent duplicating the key inside the object.
Request
Can the docs supply a recommended approach to this, as it seems like a fairly common pattern?
Issue Analytics
- State:
- Created 7 years ago
- Comments:6 (5 by maintainers)
Top GitHub Comments
In general I recommend hanging on to a DataSnapshot instead of a Map, since it’s a stronger (less generic) data type. The same applies for hanging on to a DatabaseReference over a key. It’s easy to mistake the meaning of a String, it’s almost impossible to do so for a DatabaseReference.
Not sure if that answers the question. Let me know if it doesn’t.
On Thu, Jan 26, 2017, 11:12 PM Sam Stern notifications@github.com wrote:
@puf for President