问题
I have several strings stored under specific reference: mReference.child(rID).child(userID2)
which I want to retrieve using childEventListener
as I am doing some task also when these string gets removed and that is only possible with onChildRemoved
of ChildEventListener
.
Here's what I have tried:
mReference.child(rID).child(userID2).addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Log.d("dataHEre", dataSnapshot.getValue().toString());
}
}
The problem is that I'm unable to retrieve data using keys
here as dataHEre
is logging out:
D/dataHEre: 28.8419556
D/dataHEre: 78.779063
D/dataHEre: 3
D/dataHEre: Railway Colony
D/dataHEre: Sleep
D/dataHEre: 12:36 AM
D/dataHEre: Superman
which are values
?
So, I want to know how can I retrieve data here using keys
and using ChildEventListener
and then assign the data retrieved to various strings?
回答1:
I think that you are doing your query in the wrong way. onChildAdded
method is retrieving you each child of a specific value (userID2 I suppose). If that is what you want, then just use a onValueEventListener()
to retrieve the whole dataSnapshot of your userId2 node each time that it changes.
If you want to retrieve the data just once, you should use onSingleValueEventListener()
. And OnChildEvent()
is used to retrieve lists of data where you want to track each of the child individually. For example if you attach an OnChildEventListener
to mReference.child(rID)
you will get a OnChildAdded
for each userId, what is pretty usefull like for example fill a RecyclerView
or a ListView
being able to update each item individually together with your Firebase Data.
If i'm not wrong what you want is just get updates of your userId2
reference, in that case attach a OnValueEventListener
to that reference and you will get a call each time a value is modified, deleted, or added.
firebaseDatabaseRef.addValueEventListener(new ValueEventListener() {
@Override public void onDataChange(DataSnapshot dataSnapshot) {
customPOJO customPOJO = dataSnapshot.getValue(YourCustomPOJO.class);
customPOJO.getName();
customPOJO.getEmail();
customPOJO.getfavoriteFood();
//and so on....
}
@Override public void onCancelled(DatabaseError databaseError) {
}
});
来源:https://stackoverflow.com/questions/41842681/how-to-retrieve-value-from-the-highest-last-level-node-using-childeventlistener