简体   繁体   English

从 Firebase 读取实时数据

[英]Read real-time data from Firebase

So I have come across a problem and I seem to not be able to figure it out.所以我遇到了一个问题,我似乎无法弄清楚。 I am using Firebase Auth the problem with that firebase will assign a generated user id, so I have made a Realtime Database to have user info and store a unique username.我正在使用 Firebase 验证 firebase 将分配生成的用户 ID 的问题,因此我创建了一个实时数据库来获取用户信息并存储唯一的用户名。 Now I am having a hard time reading the username from the database.现在我很难从数据库中读取用户名。 Any suggestions on how can I read the username and not the user ID generated by Firebase Auth?关于如何读取用户名而不是 Firebase Auth 生成的用户 ID 的任何建议?

在此处输入图像描述

//here I have it read the last 4 digits of user ID
    public void readUserName(){

        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
        if (user != null) {

            String name = user.getUid();
            String lastFourDigits = "";
            if (name.length() > 4)
            {
                lastFourDigits = name.substring(name.length() - 4);
            }
            else
            {
                lastFourDigits = name;
            }
            setUser.setText(lastFourDigits);
        }
       

    }

When the data is successfully written in the database, you can simply read it by creating a reference that points to the UID node (05KR...CPZ2) of the user and by attaching a listener as shown in the following lines of code:当数据成功写入数据库时,您可以通过创建一个指向用户的 UID 节点 (05KR...CPZ2) 的引用并附加一个侦听器来简单地读取它,如以下代码行所示:

String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("USERSINFO").child(uid);
uidRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DataSnapshot> task) {
        if (task.isSuccessful()) {
                String username = task.getResult().child("username").getValue(String.class);
                Log.d(TAG, username);
        } else {
            Log.d(TAG, task.getException().getMessage()); //Don't ignore potential errors!
        }
    }
});

The result in the logcat will be: logcat 中的结果将是:

suhash

One thing to notice is that the "uid" object represents the user ID that comes from the authentication process (05KR...CPZ2).需要注意的一件事是“uid”object 代表来自身份验证过程的用户 ID (05KR...CPZ2)。

You can create another child in your database having username and userid relations and then you can get userid from username, something like this您可以在您的数据库中创建另一个具有用户名和用户 ID 关系的孩子,然后您可以从用户名中获取用户 ID,就像这样

  "userReferences": {
      "myUserName1": "myUserId1",
      "myUserName2": "myUserId2"
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM