When you store user data,store it with uid. just like json object. uid as key and user data as value. Then you can get the firebaseDatabasereference using this uID.
{
"users": {
"uid_of_first_user": {
"username": "usernam",
"email": "bobtony"
},
"uid_of_second_user": {
"username": "usernam",
"email": "bobtony"
},
}}
use the below code to get the value
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("users/uid_of_first_user");
// Read from the database
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
User value = dataSnapshot.getValue(User.class);
Log.d(TAG, "Value is: " + value);
}
@Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});
create User.class. Each variables name must be same as in firebase. and also dont forget to create default constructor. just like below
public class User {
String username;
String email;
public User() {
}
public User(String username, String email) {
this.username = username;
this.email = email;
}
}
if you want to get all users data. Follow the below code.
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("users");
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
// TODO: handle the post
User value = userSnapshot.getValue(User.class);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
// ...
}
});
onAuthStateChangedlistener ? - iamkdblueimplementanything? - iamkdbluecode? - iamkdblue