如何为从Firestore检索的数据分配Class?

时间:2019-03-22 17:04:45

标签: java firebase firebase-authentication google-cloud-firestore

这是我从Firestore中检索数据的代码。

    private FirebaseFirestore db = FirebaseFirestore.getInstance();
    private DocumentReference dataRef = db.collection("users").document(currentUser);

    dataRef.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
            @Override
            public void onSuccess(DocumentSnapshot documentSnapshot) {
                if(documentSnapshot.exists()){
                    navUserName.setText(documentSnapshot.getString("fullname"));
                    navGmail.setText(documentSnapshot.getString("email"));
                } else {
                    Log.i("current user data: ","Not Found");
                }
            }
        });

我想首先将此数据分配给类用户对象,然后再从类用户对象中检索它。我该怎么办?

1 个答案:

答案 0 :(得分:1)

根据您的评论,如果要使用User对象将数据添加到数据库中,要取回数据,可以将DocumentSnapshot对象映射到User对象使用以下代码行:

String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DocumentReference dataRef = db.collection("users").document(uid);
dataRef.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
    @Override
    public void onSuccess(DocumentSnapshot documentSnapshot) {
        User user = documentSnapshot.toObject(User.class);
        Log.d(TAG, user.getFullname());
    }
});