简体   繁体   English

如何使用java / android从Firebase ONCE读取数据?

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

I'm trying to use the Java API to read data from a Firebase database in an Android application in the onCreate() event. 我正在尝试使用Java API从onCreate()事件中的Android应用程序中的Firebase数据库中读取数据。 In other words, I'm trying to do the simplest read possible, the equivalent of ... 换句话说,我正在努力做最简单的阅读,相当于......

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

});

...in the Javascript API. ...在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. 我正在尝试使用addEventListenerForSingleValueEvent()方法,但它似乎要我覆盖onDataChange()方法,这不是我想要的。 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. ..就像我在Javaxcript API中使用ref.once('value', function(snapshot)事件一样。

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). 如果你执行addListenerForSingleValueEvent,你的被覆盖的onDataChange方法将被调用一次,使用DataSnapshot,就像你想要的那样(就像“ref.once('value'...)”那样)。

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()) {
            ...
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM