Android – retrieves specific data from the firebase database
I am using the firebase database and Java to create a chat application on Android. Whenever a user registers for the first time, it will store his user name in the database under the node user / userid / profile / username. The user name is stored in the user class. This is the location where the user name value is stored. However, when I try something similar
mDatabase.child("users").child(UserID).child("profile").child("username").toString();
This gives me the path of the user name, but not the user name itself. Who knows how to get the value of the user name itself?
Editor: I made a mistake when I ran
DataSnapshot.child("users").child(mUserID).child("profile").child("username").getValue().toString();
The following is what my firebase database displays under userid
resolvent:
You don't get the right value. You need to attach a listener to your child and get updates. You do this:
// Get a reference to your user
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("server/path/to/profile");
// Attach a listener to read the data at your profile reference
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Profile profile = dataSnapshot.getValue(Profile.class);
System.out.println(profile.getUsername());
}
@Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read Failed: " + databaseError.getCode());
}
});
You can find more information and examples on the firebase website. Please note that you have not requested to get data from firebase. You attach a listener to a child and then get data from the listener. This example assumes that you have a profile model and a method to get a user name. This will return your profile object and enable you to get any data you need from it