Laith
Laith

Reputation: 81

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?

enter image description here

//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);
        }
       

    }

Upvotes: 1

Views: 54

Answers (2)

Alex Mamo
Alex Mamo

Reputation: 138824

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

Upvotes: 1

Shayan Samad
Shayan Samad

Reputation: 304

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"
  }

Upvotes: 0

Related Questions