如何在Android Studio中从Firebase实时数据库中显示已登录用户的数据。

huangapple go评论76阅读模式
英文:

how to display logged in user data from Fire base Real time database in android studio

问题

public class userinfo extends AppCompatActivity {

    TextView t1, t2, t3, t4, t5;
    DatabaseReference oref;
    FirebaseAuth auth;
    FirebaseUser user;
    String uid, email;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_userinfo);

        auth = FirebaseAuth.getInstance();
        user = auth.getCurrentUser();
        uid = user.getUid();
        email = user.getEmail();
        t1 = (TextView) findViewById(R.id.l11);
        t2 = (TextView) findViewById(R.id.l22);
        t3 = (TextView) findViewById(R.id.l33);
        t4 = (TextView) findViewById(R.id.l44);
        t5 = (TextView) findViewById(R.id.l55);

        oref = FirebaseDatabase.getInstance().getReference().child("Donor");
        oref.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                String name = dataSnapshot.child("name").getValue().toString();
                String bldgrp = dataSnapshot.child("bloodgroup").getValue().toString();
                String mob = dataSnapshot.child("mobile").getValue().toString(); // It seems "mobile" field is missing in the provided data.
                String eid = dataSnapshot.child("email").getValue().toString();
                String add = dataSnapshot.child("address").getValue().toString();
                t1.setText(name);
                t2.setText(bldgrp);
                t3.setText(mob);
                t4.setText(eid);
                t5.setText(add);

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
    }
}

(Note: The provided data lacks the "mobile" field in the "Donor" structure. The code assumes it's present, but it's not included in the provided example.)

英文:

Based on logged in user i want to display their information like name, address, bloodgroup etc.
My database structure is like the below.

Donor:

 O+:
einsein:
name: einstein
email: einstein@gmail.com
bloodgroup: O+
age: 20
address: 11/237
A-:
thamizh:
name: thamizh
email: thamizh@gmail.com
bloodgroup: A-
age: 21
address: 11/23.
public class userinfo extends AppCompatActivity {
TextView t1,t2,t3,t4,t5;
DatabaseReference oref;
FirebaseAuth auth;
FirebaseUser user;
String uid,email;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_userinfo);
auth = FirebaseAuth.getInstance();
user = auth.getCurrentUser();
uid = user.getUid();
email = user.getEmail();
t1 = (TextView) findViewById(R.id.l11);
t2 = (TextView) findViewById(R.id.l22);
t3 = (TextView) findViewById(R.id.l33);
t4 = (TextView) findViewById(R.id.l44);
t5 = (TextView) findViewById(R.id.l55);
oref = FirebaseDatabase.getInstance().getReference().child("Donor");
oref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
String  name = dataSnapshot.child("donorID").getValue().toString();
String  bldgrp = dataSnapshot.child("bloodgroup").getValue().toString();
String  mob = dataSnapshot.child("mobile").getValue().toString();
String  eid = dataSnapshot.child("email").getValue().toString();
String  add = dataSnapshot.child("address").getValue().toString();
t1.setText(name);
t2.setText(bldgrp);
t3.setText(mob);
t4.setText(eid);
t5.setText(add);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
}

答案1

得分: 1

以下是翻译好的部分:

目前你的代码从数据库加载了所有用户,然后试图从 /Donor 节点中读取其中一个用户的属性。这样是行不通的。

至少你需要在 onDataChange 中循环遍历用户:

oref = FirebaseDatabase.getInstance().getReference().child("Donor");
oref.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot snapshots) {
        for (DataSnapshot dataSnapshot: snapshots.getChildren()) {
            String name = dataSnapshot.child("donorID").getValue().toString();
            String bldgrp = dataSnapshot.child("bloodgroup").getValue().toString();
            String mob = dataSnapshot.child("mobile").getValue().toString();
            String eid = dataSnapshot.child("email").getValue().toString();
            String add = dataSnapshot.child("address").getValue().toString();
            t1.setText(name);
            t2.setText(bldgrp);
            t3.setText(mob);
            t4.setText(eid);
            t5.setText(add);
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        throw databaseError.toException(); // 不要忽略错误
    }
});

上述代码仍然从 /Donor 获取所有子节点,但现在通过循环遍历并在文本视图中设置属性。由于你只有一个用户的文本视图,每次都在覆盖先前的值。所以最终你将只会有 JSON 数据中最后一个用户的属性。这并不是你想要的,但至少比你当前的情况要好。


接下来,你需要加载只想要显示的单个用户的数据。这需要你能够识别出这个单个用户。

最常见的方法是将数据存储在数据库中,使用该用户的 UID 作为键。因此:

Users: {
  "uidOfUser1": { ... },
  "uidOfUser2": { ... },
  "uidOfUser3": { ... }
}

通过这种结构,你可以通过以下方式获取当前登录用户的数据引用:

String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
oref = FirebaseDatabase.getInstance().getReference()
                       .child("Donor")
                       .child(uid);

如果将监听器添加到这个引用上,你可以移除我们刚刚添加的循环,因为你只加载一个用户的数据。


那么问题是:如果你没有将用户信息存储在他们的 UID 下怎么办?
在这种情况下,我建议首先考虑重组数据,因为将用户数据存储在 UID 下是一种获取快速且简便查找的惯用方法。

但有时你真的无法重组数据,在这种情况下,你可以执行数据库查询来查找用户的节点。为了能够使用查询,你必须知道用户的一个(最好是唯一的)属性值。

假设你知道他们的电子邮件地址。你可以使用以下代码获取该电子邮件地址的节点:

FirebaseDatabase.getInstance().getReference()
                .child("Donor")
                .orderByChild("email").equalTo("einstein@gmail.com");

当你将监听器附加到这个查询上时,可能会再次得到多个结果,所以你需要使用我们上面添加的同样循环。

英文:

Right now your code is loading all users from the database, and then tries to read the properties for one of those users from the /Donor node. That won't work.

At the very least you'll need to loop over the users in your onDataChange:

oref = FirebaseDatabase.getInstance().getReference().child("Donor");
oref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshots) {
for (DataSnapshot dataSnapshot: snapshots.getChildren()) {
String  name = dataSnapshot.child("donorID").getValue().toString();
String  bldgrp = dataSnapshot.child("bloodgroup").getValue().toString();
String  mob = dataSnapshot.child("mobile").getValue().toString();
String  eid = dataSnapshot.child("email").getValue().toString();
String  add = dataSnapshot.child("address").getValue().toString();
t1.setText(name);
t2.setText(bldgrp);
t3.setText(mob);
t4.setText(eid);
t5.setText(add);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
throw databaseError.toException(); // never ignore errors
}
});

The above code still gets all child nodes from /Donor, but now loops through them and sets the properties in the text view. Since you only have text views for one user, you are overwriting the previous values each time. So in the end you'll have the properties for the last user from the JSON. That's not what you want, but at least it's better than what you currently have.


Next up is loading only the data for the single user that you want to display. This requires that you can identify that single user.

The most common way to do this, is to store the data in your database under the UID of that user. So:

Users: {
"uidOfUser1": { ... },
"uidOfUser2": { ... },
"uidOfUser3": { ... }
}

With this type of structure you can get a reference to the data for the currently signed in user with:

String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
oref = FirebaseDatabase.getInstance().getReference()
.child("Donor")
.child(uid);

If you add the listener to this reference, you can remove the loop we just added, since you're only loading data for one user.


That leaves the question: what to do if you didn't store the user info under their UID?
In that case, I'd recommend first considering restructuring the data, as storing user data under UIDs is the idiomatic way to get fast and easy lookups.

But sometimes you really can restructure, and in that case you can perform a database query to find the node(s) for a user. To be able to use a query, you must know the value of one (preferably unique) property of the user.

Say that you know their email address. You can then get the node(s) for that email address with:

FirebaseDatabase.getInstance().getReference()
.child("Donor")
.orderByChild("email").equalTo("einstein@gmail.com");

When you attach your listener to this query, you may get multiple results again, so you need the same for loop that we added above.

huangapple
  • 本文由 发表于 2020年4月4日 23:45:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/61030620.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定