Reputation: 81
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);
}
}
Upvotes: 1
Views: 54
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
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