如何使用java / android从Firebase ONCE读取数据? [英] How to read data from Firebase ONCE using java/android?

查看:103
本文介绍了如何使用java / android从Firebase ONCE读取数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用Java API从onCreate()事件中的Android应用程序中的Firebase数据库中读取数据。换句话说,我试图做最简单的阅读,相当于...

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) {

});

...在Javascript API中。我试图使用addEventListenerForSingleValueEvent()方法,但它似乎希望我覆盖onDataChange()方法,这不是我想要的。当程序执行到达此行时,无论数据库事件如何,我都希望得到数据。这是我的(未完成)函数....

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

..就像我正在使用 ref.once('value',function(snapshot)事件在Javaxcript API中。

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

推荐答案

这是正确的方法,你在正确的轨道上,命名只是一个有点混乱(对不起!)如果你做了addListenerForSingleValueEvent,你重写的onDataChange方法将被调用一次, DataSnapshot,就像你想要的(就像ref.once('value'...)一样)。

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).

所以你应该能够做到:

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

这篇关于如何使用java / android从Firebase ONCE读取数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆