1

enter image description here

Say I have above Firebase Database. I want to get the contact object and each of the fields using the Firebase Auto-Generated Key. How to do it?

I imagined something like:

Query ref = FirebaseDatabase.getInstance().
    getReference("contacts").orderByKey().equalTo("-KTwyKpIifsYAZiZd861");

And maybe use it like this : (Btw, below is not the actual code, since getValue() doesn't exist. It's just to represent what I'm trying to do.)

String name = ref.getValue("name");
String city = ref.getValue("city);
// and so on.

So, how to retrieve values of individual fields in Firebase?

Moses Aprico
  • 1,951
  • 5
  • 30
  • 53

1 Answers1

2

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.

pawegio
  • 1,722
  • 3
  • 17
  • 29
  • Hi there. Btw I read the doc, and have a question if you don't mind. What is the design background of using event to read data? Because it seems weird to use event just to retrieve data. (I don't mean to invalidate your answer, I just want to see the reason behind this) – Moses Aprico Oct 13 '16 at 08:21
  • Another one, why the constructor of class `Contact` is `public Post(){}` and not `public Contact(){}`? – Moses Aprico Oct 13 '16 at 08:22
  • 2
    *firebaser here* Data is loaded from the database asynchronously. Since it may take some time for the data to become available, this happens without blocking your code. Once the data is loaded, we invoke your callback (`onDataChange() in this case) with the data. This is an incredibly common pattern for internet-based APIs (and most GUIs before that). – Frank van Puffelen Oct 13 '16 at 08:23
  • yes, `Post()` constructor was a copy-paste from docs, thanks @FrankvanPuffelen for edit – pawegio Oct 13 '16 at 08:25
  • @FrankvanPuffelen Hey thanks for the enlightment, tbh I'm new to internet-based coding. So, if I want to show the retrieved contact.name in a `TextView`, I better need to somehow show a loading animation (or some sort), as long as the value is still null / not yet retrieved (and disable the loading animation in the onDataChanged)? If the answer of this is "yes" then I think I got your point – Moses Aprico Oct 13 '16 at 08:28
  • 1
    Yes, you'll indeed need to cater for the asynchronous nature of the API in your code. Your approach sounds good. Also see: http://stackoverflow.com/questions/33203379/setting-singleton-property-value-in-firebase-listener – Frank van Puffelen Oct 13 '16 at 08:39