繁体   English   中英

侦听器不适用于 Java 中的 firebase 数据引用

[英]Listener not working for firebase datareference in java

import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.database.*;
import com.google.gson.Gson;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.logging.Logger
/**
*
* @author adnan
*/
public class Json_Reader {

private final static Logger log
        = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);

public static void intializeFirebase() throws FileNotFoundException, IOException {

    FileInputStream serviceAccount =
            new FileInputStream("/home/adnan/Downloads/cryleticstest-firebase-adminsdk-avbul-f5ea5a09ca.json");

    FirebaseOptions options = new FirebaseOptions.Builder()
            .setCredentials(GoogleCredentials.fromStream(serviceAccount))
            .setDatabaseUrl("https://cryleticstest.firebaseio.com")
            .build();

    FirebaseApp.initializeApp(options);

    final FirebaseDatabase database = FirebaseDatabase.getInstance();
    System.out.println(FirebaseApp.getApps());
    DatabaseReference ref = database.getReference();
    ref.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            System.out.println(dataSnapshot.getChildrenCount());
            Object object = dataSnapshot.getValue(Object.class);
            String json = new Gson().toJson(object);
            log.info(json);
        }

        @Override
        public void onCancelled(DatabaseError error) {
            log.info("error");

        }
    });


}


public static void main(String[] args) throws IOException {

    intializeFirebase();

}
 }

我正在尝试连接我的 firebase 数据库并从那里获取 JSON 结构。 但是我的 ref(reference variable) 中的 Listener 不起作用。 我猜该程序已连接到 Firebase 控制台,但由于侦听器无法正常工作,因此无法获取任何我认为的内容。 onDataChanged 或 onCancelled 方法均无效。 我的 Firebase 实时数据库的快照,

如果我没记错的话,Java 程序将退出而不等待数据加载。 您必须使用一些 Java 同步原语显式使其等待,例如:

final CountDownLatch sync = new CountDownLatch(1);

DatabaseReference ref = database.getReference();
ref.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        System.out.println(dataSnapshot.getChildrenCount());
        Object object = dataSnapshot.getValue(Object.class);
        String json = new Gson().toJson(object);
        log.info(json);
        sync.countDown();
    }

    @Override
    public void onCancelled(DatabaseError error) {
        log.info("error");
        sync.countDown();
    }
});

sync.await();

另见:

暂无
暂无

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

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