You can create a Contact
class:
@IgnoreExtraProperties
public class Contact {
public String address;
public String city;
public String code_name;
public String name;
public Contact() {
}
}
and get a value using ValueEventListener
:
mDatabase = FirebaseDatabase.getInstance().getReference();
// ...
mDatabase.child("contacts").child("-KTwyKpIifsYAZiZd861").addListenerForSingleValueEvent(
new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Contact contact = dataSnapshot.getValue(Contact.class);
String name = contact.name; // "John Doe"
String city = contact.city; // "Texas"
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
See official docs.
More details written by the asker, according to Frank van Puffelen's comment:
If anyone read this in the future, and confused because of why retrieving data from Firebase required an event (like me), it's because when we load something from the internet, we can't always expect it to be instantly loaded. That's why we need to deal with it asynchronously, and in this Firebase case, using the event answered above.
For example, before you attach the ValueEventListener()
to retrieve the data, you can show the user a loading animation, which you disable when onDataChange()
or onCancelled()
is called. This way, your user will know that the data is being loaded and when it'll be finished.