Firebase with java (non-android) 检索信息 [英] Firebase with java (non-android) retrieve information

查看:23
本文介绍了Firebase with java (non-android) 检索信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试使用 java 代码(非 android)获取 firebase 数据库的数据.我使用了与在 android 应用程序中检索相同的方法.但它没有获取数据.

I have been trying to get my data for firebase database using java code(non-android). I used same method how I retrieved in android app. But its not getting data.

    Firebase firebase = new Firebase("https://------.firebaseIO.com");
    firebase.addValueEventListener(new ValueEventListener(){
        @Override
        public void onDataChange(DataSnapshot ds) {
            long i = ds.child("Users").getChildrenCount();
            userlist = new String[(int)i];
            int j = 0;
            for( DataSnapshot each_ds : ds.getChildren() ){
                userlist[j] = each_ds.child("username").getValue().toString();
                System.out.println(userlist[j]);
                j++;
            }
        }

        @Override
        public void onCancelled(FirebaseError fe) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }
    });

推荐答案

Firebase 客户端在单独的线程中连接到服务器,并开始在那里侦听数据.当没有更多代码要执行时,程序的主线程会继续并退出,这通常发生在 Firebase 取回其第一个数据之前(可能需要几秒钟).

The Firebase client makes its connection to the server in a separate thread and starts listening for data there. The main thread of your program continues and exits when there is no more code to execute, which often happens before Firebase gets its first data back (which may take a few seconds).

所以你必须等待数据回来.对于测试程序,我通常通过在程序末尾插入一个简单的 Thread.sleep() 来做到这一点:

So you'll have to wait for the data to come back. For test programs I usually do this by inserting a simple Thread.sleep() at the end of my program:

Thread.sleep(20000);

但在实际程序中,您可能想找出更好的退出条件.比如这里我们使用一个CountDownLatch让主代码等待操作完成:

But in a real program you'd probably want to figure out a better exit condition. For example, here we use a CountDownLatch to make the main code wait until the operation is completed:

final CountDownLatch sync = new CountDownLatch(1);
ref.push().setValue("new value")
   .addOnCompleteListener(new OnCompleteListener<Void>() {
      public void onComplete(Task<Void> task) {
        sync.countDown();
      }
    });
sync.await();

顺便说一下,不要在 Android 中使用这种方法,因为它会阻塞主/UI 线程并使应用程序无响应.

Don't use this approach in Android by the way, as it will block the main/UI thread and leave the app unresponsive.

这篇关于Firebase with java (non-android) 检索信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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