如何在Android的Firebase数据库中从uid获取/检索多个数据?

时间:2018-07-31 12:34:59

标签: android firebase firebase-realtime-database

如何使用以下代码从Firebase获取数据?
成功登录后,出现空指针异常了吗?

DatabaseReference mref = FirebaseDatabase.getInstance().getReference().child("/Users/Students")
                    .child(FirebaseAuth.getInstance().getCurrentUser().getUid());
            mref.addValueEventListener(new ValueEventListener() {
                @SuppressLint("SetTextI18n")
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    for (DataSnapshot ds : dataSnapshot.getChildren()){

                        email = ds.child("email").getValue().toString();
                        full_name = ds.child("full_name").getValue().toString();
                        roll_number = ds.child("roll_number").getValue().toString();
                        admission_id = ds.child("admission_id").getValue().toString();
                        phone_no = ds.child("phone_number").getValue().toString();
                        branch = ds.child("branch").getValue().toString();
                        year = ds.child("year").getValue().toString();
                        semester = ds.child("semester").getValue().toString();
                        section = ds.child("section").getValue().toString();
                        course = ds.child("course").getValue().toString();
                        batch = ds.child("batch").getValue().toString();
                        dob = ds.child("dob").getValue().toString();
                        address = ds.child("address").getValue().toString();
                    }

                }

我的Firebase数据库是:

enter image description here

1 个答案:

答案 0 :(得分:3)

删除以下内容:

 for (DataSnapshot ds : dataSnapshot.getChildren()){

由于您已经可以访问uid,因此不需要在直接子级中循环以获取值。

所以只要这样做:

 public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                    email = dataSnapshot.child("email").getValue().toString();
                    full_name = dataSnapshot.child("full_name").getValue().toString();
                    roll_number = dataSnapshot.child("roll_number").getValue().toString();
                    admission_id = dataSnapshot.child("admission_id").getValue().toString();
                    phone_no = dataSnapshot.child("phone_number").getValue().toString();
                    branch = dataSnapshot.child("branch").getValue().toString();
                    year = dataSnapshot.child("year").getValue().toString();
                    semester = dataSnapshot.child("semester").getValue().toString();
                    section = dataSnapshot.child("section").getValue().toString();
                    course = dataSnapshot.child("course").getValue().toString();
                    batch = dataSnapshot.child("batch").getValue().toString();
                    dob = dataSnapshot.child("dob").getValue().toString();
                    address = dataSnapshot.child("address").getValue().toString();