Get User Node From Firebase Using The Uid In Android?
Solution 1:
I'm writing this answer according to your request from here but I see that although you are getting the uid
from the FirebaseUser
object, you are not using it at all. You are still using that random unique key provided by the push()
method. So if you want to use the uid
, your database structure should look like this:
Firebase-root
|
--- users
|
--- uid
|
--- email: "nicefawad1@gmail.com"
|
--- uid: "uid"
|
--- name: "fawad"
See, I have used the uid
that is coming as a result from the following line of code:
Stringuid= FirebaseAuth.getInstance().getCurrentUser().getUid();
In order to read this data, you have two options. The first one would be as @Gastón Saillén explained in his answer using a model class, or in a more simpler way using the String
class. So to get the name of a specific user, please use the following lines of code:
DatabaseReferencerootRef= FirebaseDatabase.getInstance().getReference();
DatabaseReferenceuidRef= rootRef.child("users").child(uid);
ValueEventListenervalueEventListener=newValueEventListener() {
@OverridepublicvoidonDataChange(DataSnapshot dataSnapshot) {
Stringname= dataSnapshot.child("name").getValue(String.class);
Log.d("TAG", name);
}
@OverridepublicvoidonCancelled(DatabaseError databaseError) {}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);
The result in your logcat will be: fawad
.
Solution 2:
You will need to create a POJO object class in order to get the atributes from that current uid user
to do that first create a class with your user variables, i will call this UserPojo.class
publicclassuserPojo {
privateString email;
privateString id;
privateString name;
publicuserPojo() {
}
publicStringgetEmail() {
return email;
}
publicvoidsetEmail(String email) {
this.email = email;
}
publicStringgetId() {
return id;
}
publicvoidsetId(String id) {
this.id = id;
}
publicStringgetName() {
return name;
}
publicvoidsetName(String name) {
this.name = name;
}
}
And then just iterate through that node and get your values this way
first declare your database reference
private DatabaseReference mDatabase;
then inside onCreate()
mDatabase = FirebaseDatabase.getInstance().getReference(); //root reference to the database
then just get the values inside the reference
mDatabase.child("collion").child(uid).addValueEventListener(newValueEventListener() {
@OverridepublicvoidonDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snapShot : dataSnapshot.getChildren()){
UserPojo user = snapShot.getValue(UserPojo.class);
//get your values inside that uidString name = polla.geName();
String email = polla.getEmail();
String id = polla.getId();
Log.e("Data: " , "" + name + "" + email+""+id);
}
}
@OverridepublicvoidonCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
thats all, any question feel free to ask
Post a Comment for "Get User Node From Firebase Using The Uid In Android?"