I'm creating a chat app on android using Firebase Database and Java. Whenever the user is first registered, it stores their username into the database under the nodes user/UserID/profile/username
. The username is stored using a User class. This is where the username value is stored. However when I try something like
mDatabase.child("users").child(UserID).child("profile").child("username").toString();
This gives me the path to the username but not the username itself. Does anybody know how to get the value of the username itself?
EDIT: It gives me an error when I run
DataSnapshot.child("users").child(mUserID).child("profile").child("username").getValue().toString();
Here is what my Firebase database shows under the UserID.
You aren't getting the value properly. You need to attach a listener to you child and get updates. You do that like 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. Keep in mind that you don't make requests to get data from Firebase. You attach listeners to the children and then get the data from the listener. This example assumes that you have a Profile
model, with a method to get the username. This would return your Profile
object and would enable you to get whatever data you need off of that object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With