Skip to content Skip to sidebar Skip to footer

How To Access The Key Of Child By It's Position In Custom Adapter Class

I am trying to access the Key through which my post information is stored in firebase. All I need is to access the Key like we do by using the library. final String TheKey = getRef

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 DataSnapshots 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:

Post a Comment for "How To Access The Key Of Child By It's Position In Custom Adapter Class"