0

I have a database like this,

Users
    COd3XoRnWOMRIFrbYSrNMZjm2Jj2
        admin: false
        email: "test@test.com"
        name: "aa"
        surname: "aa"
        username: "test"
    KtUAjavm3TUmonRXl37CS4ePhuK2
        admin: false
        email: "test2@test.com"
        name: "aa"
        surname: "bb"
        username: "test"

And I have a User class. I want to fetch the user data from database, create a User instance and using user.getUsername() method, get the username that I fetched from database. But when use the code below, user.getUsername() returns null.

User user = new User("USER_ID");
user.getUsername();

This is my constructor,

public User(String id) {
        UID = id;
        Users = database.getReference("Users").child(id);
        Users.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if(dataSnapshot.exists()) {
                    Log.d(TAG, UID);
                    username = (String) dataSnapshot.child("username").getValue();
                    email = (String) dataSnapshot.child("email").getValue();
                    surname = (String) dataSnapshot.child("surname").getValue();
                    name = (String) dataSnapshot.child("name").getValue();
                    admin = (Boolean) dataSnapshot.child("admin").getValue();
                } else {
                    Log.e(TAG, "Invalid UID");
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
            }
        });
    }
Naim Berk Tumer
  • 129
  • 3
  • 11
  • 1
    That means the user data hasn't been loaded yet. The data is loaded from the Firebase Database asynchronously, so you can't simply assume that it's there. Your `onDataChange()` fires *after* your call to `getUsername()`. See http://stackoverflow.com/questions/33203379/setting-singleton-property-value-in-firebase-listener – Frank van Puffelen Mar 26 '17 at 01:04
  • And one more thing, you use `i` as UID but the string passed is `id`. Is it intentional or just typo? – koceeng Mar 26 '17 at 01:07
  • It's just a typo here. So is there any way to do that? – Naim Berk Tumer Mar 26 '17 at 09:52
  • I think Frank already gave you the answer. Please read the link, it contains basic and very fundamental concept of Firebase that I think you'll need not just in this problem – koceeng Mar 26 '17 at 14:34

0 Answers0