Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dataSnapshot has the object but getValue() will return null

So I'm struggling with this issue for about three hours now.
I have this user class

public class User {
private String user_id;
private String userName;
private long phoneNumber;

public User() {
}

public User(String user_id, String userName, long phoneNumber) {
    this.user_id = user_id;
    this.userName = userName;
    this.phoneNumber = phoneNumber;
}

And I want to fetch some instances of this class from Firebase Database I am using this code to do so:
database reference;

User currentUser;
DatabaseReference database = FirebaseDatabase.getInstance().getReference(); 
DatabaseReference usersRef = database.child("users");

query code:

Query query = usersRef.orderByChild("user_id").equalTo(user_id);
                query.addListenerForSingleValueEvent (new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                         currentUser = dataSnapshot.getValue(User.class);
}

Funny thing: this code actually worked once but I made some changes I guess, and now the getValue() returns null;
this is my database in firebase
enter image description here
and when I debug the app the dataSnapshot actually contains the object I am looking for
enter image description here
but the currentUser will be an object with all its fields null;
enter image description here
any ideas? I'm getting really frustrated already :( Thanks in advance!

like image 648
knightLoki Avatar asked Dec 05 '22 14:12

knightLoki


1 Answers

You need to iterate over dataSnapshot.getChildren(...for example

                for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
                    User user = childSnapshot.getValue(User.class);
                 }
like image 200
John O'Reilly Avatar answered Apr 27 '23 02:04

John O'Reilly