0

I've made a class to work with my firebase databse. At the current moment it gives me opportunity to get some user data from my DB. It totally works, when I get my object in the onDataChange method (I use Log.w to check that), but when I try to use userData, that my getUserData returns, it becomes null. Why does it happen? Here is my code:

import android.util.Log;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
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;

/**
 * Created by Aldres on 25.02.2018.
 */

public class DBtools {

    private FirebaseAuth mAuth;
    private FirebaseUser mUser;
    private FirebaseDatabase mDb;
    private DatabaseReference ref;
    private String uid;
    private User userData;

    private void initDb(){
        mAuth = FirebaseAuth.getInstance();
        mUser = mAuth.getCurrentUser();
        if (mUser!=null) {
            uid = mUser.getUid();
        }
        mDb = FirebaseDatabase.getInstance();
        ref = mDb.getReference().child("users").child(uid);
    }

    public User getUserData(){
        initDb();
        ref.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                userData = dataSnapshot.getValue(User.class);
                Log.w("UserData",userData.getExp() + userData.getUsername() + userData.getGender());
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
            }
        });
        return userData;
    }
}
Aldres
  • 185
  • 1
  • 3
  • 16
  • 1
    Data is loaded from Firebase asynchronously. In this case that means that you're returning the `userData` **before** any data has been added to it. Since I just answered another question about this, I'll refer you there: https://stackoverflow.com/questions/49211710/modifying-a-list-from-nested-ondatachange/49212021#49212021 Especially check out the links, which point to many other questions about the topic. – Frank van Puffelen Mar 10 '18 at 19:55
  • Thank you. Now I understand. Yeah, problem is in asynchronous data loading – Aldres Mar 10 '18 at 19:56

0 Answers0