How To Access The Key Of Child By It's Position In Custom Adapter Class
Solution 1:
I'm assuming that by "the library you mean FirebaseUI, specifically its adapters for showing lists of content from the Firebase Realtime Database in Android views.*
You'll have to do the same thing that FirebaseUI does, which is keep track of the positions of both the keys and the values of all items. FirebaseUI handles this in the FirebaseArray
class, by simply storing the DataSnapshot
s from Firebase in a list.
Most developers however seem to prefer to keep the value from their snapshots in custom Java classes, for more direct consumption by their adapter, in which case you'll typically have something like:
List<Post> posts;
The Post
class in here has the properties for each post from your database, and you'd get it with something like snapshot.getValue(Post.class)
. But since Post
only has the value of the object, you're missing the key.
A very simple way to also track the keys, is by adding a second list:
List<String> keys;
Now whenever you add a post to the list, you also add a key to the other list. Something like:
posts.add(snapshot.getValue(Post.class));
keys.add(snapshot.getKey());
And once you have both lists, you can find the key by either its index/position in keys
or by first looking up a post in posts
and then looking up the corresponding key by its index.
Also see:
- How can I remove specific item from List when data in firebase realtime db is removed? (showing a similar approach)
- Get parent key value on click of child in recyclerview from firebase database (showing more context of building an adapter)
Post a Comment for "How To Access The Key Of Child By It's Position In Custom Adapter Class"