shikher.mishra shikher.mishra - 19 days ago 21
Android Question

Retrieving data from Firebase database is returning null values

I have created a database in Firebase with rules as follows:

{
"rules": {
".read": true,
".write": true
}
}


And my database is shown in the form of JSON data like this:

fieldglass-aeca7
0
age: 23
name:"shikher"
1
age:24
name:"samarth"

fieldglass-aeca7
-KWm_3CF1pSVtuy9nhFF
age:12
name:"shikhermishra"
-KWmaVs4frXpS_1lVhcj
age:13
name: "Shiker"


Now I have written a code to read the data from the database. And also a class User which has 2 data members age,name.

User class is as follows:

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;




public class User {

public int age;
public String name;

public User(){
}
public User(int age,String name)
{
this.name=name;
this.age=age;
}

public void setAge(int age) {
this.age = age;
}

public void setName(String name) {
this.name = name;
}


public int getAge() {
return age;
}

public String getName() {
return name;
}
}


And my database fetching code is like:

FirebaseDatabase database=FirebaseDatabase.getInstance();
DatabaseReference reference=database.getReference("fieldglass-aeca7");

reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user=dataSnapshot.getValue(User.class);
Log.d("user info---@@*******",String.valueOf(user.getAge()));



assert tv != null;
assert tv1 != null;
tv.setText(String.valueOf(user.age));
tv1.setText(user.name);


}

@Override
public void onCancelled(DatabaseError databaseError) {

Log.d("The read failed",databaseError.getDetails());
}
});


I am trying to fetch the age and name and display it on the 2
TextView
s I have.

But the output I am getting is

user.age=0 and user.name=null.


I want to fetch all the data which is present inside :

fieldglass-aeca7
......

fieldglass-aeca7


this key value.

I want all the data inside the above path shown. How can I get it?

Answer

I think, The received DataSnapshot is like an array, you have to loop for its children first.

The right Scenario might be like this:

if (dataSnapshot.hasChildren())
{
     for (DataSnapshot child : dataSnapshot.getChildren)
     {
          User user = child.getValue(User.class);

          // your actions here: 
          assert tv != null;
          assert tv1 != null;
          tv.setText(String.valueOf(user.age));
          tv1.setText(user.name);

      }
 }

NOTE: dataSnapShot.getChildren just returns Iterable<DataSnapshot>, hence no change just loop.