Get the values of a child - android

root
-messages
--LIB38128eG7v
-receiverID: "yoon"
-senderID: "kim"
-text: "good day"
--LIB36334eG9e
-receiverID: "yoon"
-senderID: "kim"
-text: "good night"
this is my firebase database.
and there is a class named Chat, which has receiverID, senderID, text.
I can get all the data of messages by
ref.child("messages").addChildEventListener(new ChildEventListener(){
public void onChildAdded(Datasnapshot dataSnapshot, String s){
Chat chat = dataSnapshot.getValue(Chat.class);
mChat.add(chat); //mChat is an array of Chat
....
}
But I want to get the data of LIB38128eG7v, not the all of the messages. In this case, how can I get one of the child's child values?
Is there any way not using listener?

There is no way to get the data from a Firebase database without using a listener. Everything in Firebase is about listeners. To get the data under -LIB38128eG7v, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference messageIdRef = rootRef.child("messages").child("-LIB38128eG7v");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Chat chat = dataSnapshot.getValue(Chat.class);
Log.d("TAG", chat.getText());
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
messageIdRef.addListenerForSingleValueEvent(valueEventListener);
The output in your logcat will be: good day.

I think this way it will work
DatabaseReference rootRef =
FirebaseDatabase.getInstance().getReference().child("messages").child("-
LIB38128eG7v");
rootRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
//your code
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

Related

How to read only one value from Firebase Database in Android Studio?

This is my database in Firebase Database:
How can I read the value of only a1 from my Firebase Database in my Android app and store it in a String variable ra1? Example Java code using the given database would be really helpful.
Thank You.
In your case, you just want to retrieve that String ONCE, and not listen for any changes.
So, what you do:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.addListenerForSingleValueEvent(new ValueEventListener(){
#Override
public void onDataChange(DataSnapshot dataSnapshot){
String value = dataSnapshot.child("a1").getValue(String.class); //This is a1
}
});
Initiliaze root and add childeventlistener:
DatabaseReference root = FirebaseDatabase.getInstance().getReference().child("morpion_c76af");
root.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
if(dataSnapshot.getKey().equals("a1")) {
String a = (String) dataSnapshot.getValue()
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Hope this helps.

How to know number of items returned by query in Firebase

I have this query in my Firebase
mDataBase = FirebaseDatabase.getInstance().getReference("animals);
query = mDataBase.orderByChild("height").limitToLast(20);
query.addChildEventListener(new AnimalsEventListener());
My listener
private class AnimalsEventListener implements ChildEventListener{
private AnimalsEventListener(){
}
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Animals details = dataSnapshot.getValue(Animals.class);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
}
How can I get the size of all animals that matched the query before working on dataSnapShot? sometimes they can be less than 20;
It's not possible to know children count using ChildEventListener, use ValueEventListener instead.
public class AnimalsEventListener implements ValueEventListener {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getChildrenCount() == 20) {
for (DataSnapshot dataSnapshotEntry : dataSnapshot.getChildren()) {
Animals details = dataSnapshotEntry.getValue(Animals.class);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
}
To attach this listener, use addValueEventListener() method
query.addValueEventListener(new AnimalsEventListener());
If you wanna use childEventListener i recommend u to use official FirebaseArray class.
To get the item count:
FirebaseArray mFirebaseArray = FirebaseArray(Query ref);
mFirebaseArray.getCount();

How to add real-time listener to firebase query

I've created a database to store my logs and get real-time update of my log entries for the last 1 hour
I've tried adding a real-time listener to my firebase query. Both attempt triggered once (upon start-up), but didn't trigger when a new log was added while the app is already running
Here are my code
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("logs");
long MillisInHour = 60*60*1000;//one hour
Here is the query
Query query = myRef.orderByChild("timeStamp").startAt(System.currentTimeMillis()).endAt(System.currentTimeMillis() - MillisInHour);
I've tried (Attempt #1)
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
Also (Attempt #2)
query.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
Found it. I should have used
Query query = myRef.orderByChild("timeStamp").startAt(System.currentTimeMillis() - MillisInHour)
instead.

Firebase change data from server, listen on Android

I'm playing with Firebase. Updating data in server with node.js:
var db = firebase.database()
var ref = db.ref("game")
ref.update({
"state": "state",
"counter": counter
})
The data in Firebase console updated without problem but in Android, I can't retrieve any change. I want to listen "game" node's changes but no luck.
DatabaseReference database = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = database.child("game");
ref.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Log("1");
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
Log("2");
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
Log("3");
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
Log("4");
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log("5");
}
});
There is no log in console.
Also, with ValueEventListener I'm still not seeing any change or error:
DatabaseReference ref = database.child("game");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log("1");
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log("2");
}
});
I'm clearly doing something wrong. How can I listen the data changes in FireBase?
I 'solved' the issue by re-logging by user. I guess this is a bug.
Relevant: Firebase single value event listener doesn't return

retrive data from firebase

I'm new to android developing. I tried retrieving data from firebase. which worked . but I'm unable to filter unique identifier from database results .
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myref = database.getReference("user_foods");
myref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d("foods",dataSnapshot.getValue().toString());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
results are like
XsgGhY7qUY5Qa3t8 = {food = apple} , ..... etc
I want to remove that unique identifier & just display results as
Apple , Mango ...etc
thank you
I figured the answer. If anyone has same issue use "child event listener "
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myref = database.getReference("user_foods");
myref.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Log.d("foods",dataSnapshot.getValue().toString());
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Try this:
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myref = database.getReference("user_foods");
myref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snap: dataSnapshot.getChildren()) {
Log.d('foods',dataSnapshot.child('food').getValue().toString());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
adding child() to your reference you can access an specific key in your tree. But as Frank suggests try using a POJO class to retrieve all your data from Firebase
edited: sorry i forgot you had many children, you need to make for (DataSnapshot snap: dataSnapshot.getChildren()) {//code} when your have many children in your node

Categories

Resources