How to read data from Firebase ONCE using java/android?

MassStrike picture MassStrike · Jul 28, 2013 · Viewed 31.5k times · Source

I'm trying to use the Java API to read data from a Firebase database in an Android application in the onCreate() event. In other words, I'm trying to do the simplest read possible, the equivalent of ...

ref.once('value', function(snapshot) {

});

...in the Javascript API. I'm trying to use the addEventListenerForSingleValueEvent() method, but it seems to want me to override the onDataChange() method, which is not what I want. I want to get the data out when the program execution reaches this line, regardless of database events. Here's my (unfinished) function....

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.poll_table);    

        // First get the table layout
        tbl = (TableLayout) findViewById(R.id.pollsTable);

        // Now let's create the header
        TableRow tHead = createPollsTableHeader();

        // Add header to tableLayout
        tbl.addView(tHead, new TableLayout.LayoutParams(
                LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT));

        // Add all polls in ref as rows
        polls.addListenerForSingleValueEvent(new ValueEventListener() {
            // DON'T KNOW WHAT TO DO HERE

        }
    }

I don't even think this is the correct method. I just want to be able to get a Datasnapshot that I can iterate through and get data out of, like...

for (Datasnapshot child : datasnapshot) {
}

..just as if I were using the ref.once('value', function(snapshot) event in the Javaxcript API.

Answer

Michael Lehenbauer picture Michael Lehenbauer · Jul 28, 2013

That is the right method, and you're on the right track. The naming is just a little confusing (sorry!). If you do the addListenerForSingleValueEvent, your overridden onDataChange method will be called exactly once, with a DataSnapshot, just as you wish (and just like "ref.once('value' ...)" would do).

So you should be able to do:

// Add all polls in ref as rows
polls.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot snapshot) {
        for (DataSnapshot child : snapshot.getChildren()) {
            ...
        }
    }
}