使用 Java 从 firebase 获取数据 [英] Grab Data from firebase with Java

查看:37
本文介绍了使用 Java 从 firebase 获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了下面这段代码的问题,该代码几乎是从 Firebase SDK Java 文档中逐字复制而来的.我刚接触真正的语言,例如来自 PHP 和 JavaScript 网络开发背景的 Java.

I'm having an issue with this code below which has almost verbatim been copied from the Firebase SDK Java docs to work. I'm new to a real language such as Java coming from a webdev background in PHP and JavaScript.

基本上 addListenerForSingleValueEvent 不会触发以返回数据.我注意到这一点是因为系统打印输出没有触发,因此我假设监听事件没有触发.

Basically the addListenerForSingleValueEvent isn't firing to give me back data. I noticed this because the system printout doesn't fire thus I assume that the listening event didn't fire.

我怀疑这与我对函数本身如何工作的知识有限有关,就像我缺少一些关于类和函数如何相互作用的结构知识.

I suspect that this has to do with my limited knowledge how out the function itself works, like I'm missing some structural knowledge of how the class and functions interact with each other.

如有任何帮助,我们将不胜感激.

Any help would be appreciated thank you.

class FireBase {
public static void main(String[] args) throws IOException {
    // Fetch the service account key JSON file contents
    FileInputStream serviceAccount = new FileInputStream("key.json");

    // Initialize the app with a service account, granting admin privileges
    FirebaseOptions options = new FirebaseOptions.Builder()
        .setCredential(FirebaseCredentials.fromCertificate(serviceAccount))
        .setDatabaseUrl("https://ssworks-adwords.firebaseio.com/")
        .build();
    FirebaseApp.initializeApp(options);

    // As an admin, the app has access to read and write all data, regardless of Security Rules
    DatabaseReference ref = FirebaseDatabase
        .getInstance()
        .getReference("petitions");
    ref.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            System.out.println("Before Get Value");
            Object document = dataSnapshot.getValue();
            System.out.println(document);
        }

        @Override
        public void onCancelled(DatabaseError arg0) {
            // TODO Auto-generated method stub
            System.out.println("This didn't work");
        }
    });
}

}

推荐答案

如果您有一个通过某个类的 main 函数在命令行上调用的 Java 程序,则必须在数据库侦听器触发之前阻止该 main 函数返回.否则,程序将立即终止并且侦听器永远不会触发.请务必记住,所有 Firebase 侦听器都是异步的,并且 Firebase 管理自己的守护线程以与服务器通信.

If you have a java program that's invoked on the command line via some class's main function, you have to prevent that main function from returning before the database listener fires. Otherwise, the program will immediately terminate and the listener will never fire. It's important to remember that all Firebase listeners are asynchronous, and Firebase manages its own daemon thread for communicating with the server.

对于让一个简单的程序等待监听器触发的情况,可以使用这种模式阻塞主线程等待监听器:

For the case of making a simple program wait until a listener triggers, you can use this sort of pattern to block the main thread to wait for the listener:

CountDownLatch latch = new CountDownLatch(1);
ref.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        System.out.println("onDataChange: " + dataSnapshot);
        latch.countDown();
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        System.out.println("onCanceled: " + databaseError);
        latch.countDown();
    }
});
latch.await();

使用 CountDownLatch 不是您唯一的选择.你可以做任何你想做的事情来确保进程不会停止,包括让主线程休眠的时间比监听器触发的时间长.

Using a CountDownLatch is not your only option. You can do whatever you want to make sure the process doesn't stop, including simply sleeping the main thread for longer than it takes for the listener to fire.

这篇关于使用 Java 从 firebase 获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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