如何从firebase数据库获取登录用户的数据

时间:2018-06-10 16:38:02

标签: java android firebase firebase-realtime-database firebase-authentication

我在这段代码中需要帮助。

如何从firebase数据库中获取登录的用户数据?

这些是我的代码:

public void getUserInfo(){
    mFirebaseDatabase = FirebaseDatabase.getInstance();
    mUserDatabase = mFirebaseDatabase.getReference("users");
    FirebaseUser user = mAuth.getCurrentUser();
    mUserDatabase.child(userID).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange( com.google.firebase.database.DataSnapshot datasnapshot) {
            for (DataSnapshot dataSnapshot : datasnapshot.getChildren()) {
                User user1 = dataSnapshot.getValue(User.class);

                String firstname = user1.getFirstName();
                String secondname = user1.getSecondName();
                String email = user1.getEmail();
                String enrollment = user1.getEnrollnumber();
                String branch = user1.getBranch();
                String college = user1.getCollege();

                First_name.setText(firstname);
                Second_name.setText(secondname);
                tx_Email.setText(email);
                Enroll_number.setText(enrollment);

            }
        }
        @Override
        public void onCancelled(DatabaseError firebaseError) {
            /*
             * You may print the error message.
             **/
        }
    });

}

任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:0)

据我所知,您正在将侦听器附加到单个用户的数据上。这意味着您无需在dataSnapshot.getChildren()中循环onDataChange

所以:

public void onDataChange( com.google.firebase.database.DataSnapshot snapshot) {
    User user1 = snapshot.getValue(User.class);

    String firstname = user1.getFirstName();
    String secondname = user1.getSecondName();
    String email = user1.getEmail();
    String enrollment = user1.getEnrollnumber();
    String branch = user1.getBranch();
    String college = user1.getCollege();

    First_name.setText(firstname);
    Second_name.setText(secondname);
    tx_Email.setText(email);
    Enroll_number.setText(enrollment);
}

答案 1 :(得分:0)

试试这个,在我的情况下,我的firebase中的数据库被调用"用户",with和userID是每个用户的id,使用此userID我过滤每个用户示例的数据(名称,电子邮件。 ..等)

您需要编写一个for来迭代所有字段,然后获取您需要的位置,例如position [0] = name,position [1] = email ... etc

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
    DatabaseReference idRef = rootRef.child("Users").child(userID);

final List<String> lstItems= new ArrayList<String>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
    String values = (String) ds.getValue();
    lstItems.add(values);
}

Log.d(TAG, "NAME: " + lstItems.get(0).toString());
Log.d(TAG, "EMAIL: " + lstItems.get(1).toString());

并打印出来

email = lstItems.get(0).toString();
name = lstItems.get(1).toString();

我希望它可以帮到你