简体   繁体   中英

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. 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?

在此处输入图像描述

//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:

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:

suhash

One thing to notice is that the "uid" object represents the user ID that comes from the authentication process (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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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