Reputation: 640
I have a database reference.
houseReference = FirebaseDatabase.getInstance().getReference("House");
I add an item to the db using:
houseReference.push().setValue(house);
Google firebase reference documentation says you can then get the key for the last item using
houseReference.getKey();
However, this returns House
. What am I doing wrong?
Upvotes: 2
Views: 2184
Reputation: 598708
Firebase has no concept of "the last key". But each DatabaseReference
is a reference to a path in the database, and you get the last key in that path by calling getKey()
on it. So if you call houseReference.getKey()
you indeed get house
, since that is the last key in the path that it refers to.
Now we get to the good stuff though.
When you call push()
Firebase generates (in the client) a new unique key, and return a new DatabaseReference
that point to that key under the current path. So houseReference.push()
returns a new DatabaseReference
to the new, unique, child location. And this means that you can call getKey()
on this new DatabaseReference
to get the last key of that new location.
So:
DatabaseReference newRef = houseReference.push();
System.out.println(newRef.getKey());
newRef.setValue(house);
Upvotes: 6