java - 侦听器不适用于 java 中的 firebase 数据引用
问题描述
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 方法都不起作用。
解决方案
如果我没记错的话,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();
另见:
推荐阅读
- sql - 当整列存储为文本时,如何在SQL中分隔数字和文本?
- php - 如何为 RabbitMQ PHP 任务创建 Docker 容器
- javascript - 无法使用 async 和 Foreach 处理 Firebase 获取的值
- javascript - 如何在使用 sinon 的包装器中调用对象时进行单元测试?
- shopify - 使用 Cart.js 和 Rivets.js 添加/删除购物车项目
- python - Python Multiprocessing/Pool with Selenium - 创建 webdriver 的多个副本
- javascript - 在 && 运算符中更改 CSS 样式
- javascript - Javascript slick.js轮播将多个幻灯片向后拖过第一个元素不起作用
- java - Maven 没有检测到 Reactor 构建模块中的依赖关系?
- sql - 滚动总和直到达到某个值,加上计算的持续时间