使用Firebase ListenerForSingleValueEvent获取null

时间:2018-03-10 19:52:01

标签: java android firebase firebase-realtime-database

我已经开始上课了我的firebase数据库。目前,它让我有机会从我的数据库中获取一些用户数据。它完全有效,当我在onDataChange方法中获取对象时(我使用Log.w来检查),但是当我尝试使用userData时,我的getUserData返回,它变为null。为什么会这样?这是我的代码:

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;
    }
}

0 个答案:

没有答案