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

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

问题描述

我在下面的代码中遇到了问题,它几乎逐字地从Firebase SDK Java文档复制到工作。我是新来的一个真正的语言,如来自PHP和JavaScript的webdev背景的Java。



基本上addListenerForSingleValueEvent没有发射给我回数据。我注意到这一点,因为系统打印输出不会触发,因此我认为这个监听事件并没有触发。



我怀疑这与我有限的知识有关出来的功能本身的作品,就像我错过了一些关于类和函数如何相互作用的结构知识。



任何帮助,将不胜感激谢谢。 >

  class FireBase {
public static void main(String [] args)throws IOException {
//获取服务帐户密钥JSON文件内容
FileInputStream serviceAccount = new FileInputStream(key.json);

//使用服务帐户初始化应用,授予管理员权限
FirebaseOptions选项=新的FirebaseOptions.Builder()
.setCredential(FirebaseCredentials.fromCertificate(serviceAccount))
.setDatabaseUrl(https://ssworks-adwords.firebaseio.com/)
.build();
FirebaseApp.initializeApp(options);

//作为管理员,无论安全规则如何,应用程序都可以读取和写入所有数据
DatabaseReference ref = FirebaseDatabase
.getInstance()
。 getReference( 请愿);
ref.addListenerForSingleValueEvent(new ValueEventListener(){
@Override
public void onDataChange(DataSnapshot dataSnapshot){
System.out.println(获取值之前);
Object document = dataSnapshot.getValue();
System.out.println(document);
}
$ b @Override
public void onCancelled(DatabaseError arg0) {
// TODO自动生成的方法存根
System.out.println(This does not work);
}
});


$ b


解决方案

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



对于使简单程序等待监听器触发器,你可以使用这种模式来阻止主线程等待监听器:

pre codeountDownLatch latch = new CountDownLatch (1);
ref.addListenerForSingleValueEvent(new ValueEventListener(){
@Override
public void onDataChange(DataSnapshot dataSnapshot){
System.out.println(onDataChange:+ dataSnapshot);
latch.countDown();
}
$ b $ @覆盖
public void onCancelled(DatabaseError databaseError){
System.out.println(onCanceled: + databaseError);
latch.countDown();
}
});
latch.await();

使用CountDownLatch不是您唯一的选择。你可以做任何你想要的,以确保过程不会停止,包括简单地睡主线程的时间超过了侦听器的触发。


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.

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");
        }
    });
}

}

解决方案

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();

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天全站免登陆