So in the above data structure, I want to get value Aprilia Caponord 1200
(marked in fig.). I have Firebase reference to Aprilia
(root nod
I met this case and solved the way as below:
final ChildEventListener countsListener = new ChildEventListener() { //for querying how many card created by each user in a specific period
@Override
public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
/**
* $ROOT/Apirilia/Apirilia_id/CardId/IMG_URL
* $ROOT/Apirilia/Apirilia_id/CardId/PRICE
* ^[key] :[value]
*/
if (dataSnapshot == null) {
Logger.e("!!! dataSnapshot is null");
return;
}
String apirilia_id = dataSnapshot.getRef().getParent().getKey();
Logger.d("... Apirilia_id:" + apirilia_id);
}
@Override
public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
}
@Override
public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
};
I'm appreciated to be able to give one a hand.
You're probably looking for the getKey()
method on DataSnapshot
:
mFirebaseRef = new Firebase("https://yours.firebaseio.com");
mFirebaseRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child: dataSnapshot.getChildren()) {
Log.i("MainActivity", child.getKey());
}
}
@Override
public void onCancelled(FirebaseError firebaseError) {
Log.e("MainActivity", "onCancelled", firebaseError.toException());
}
});
A few things to note here:
getChild()
in your code to getChildren()
, since there is not method getChild()
that I'm aware of.addChildEventListener
, which gives you DataSnapshots
on the lower-level nodesfor those who looking for key in firebaseUi then this code will work for u:-
firebaseadapterinstance.getRef(position).getKey();