我正在尝试通过一个简单的 Java 程序将数据添加到 firebase 实时数据库 它按照 https://firebase.google.com/docs/database/admin/save-data 中的描述正确执行
但我没有看到数据到 firebase 控制台 - 它没有被实际添加到数据库
代码
public static void main(String[] args) {
FileInputStream serviceAccount;
try {
serviceAccount = new FileInputStream("E:\\development\\firebase\\key\\svbhayani_realtimedb-98654-firebase-adminsdk-n75sy-49f62c9338.json");
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
.setDatabaseUrl("https://realtimedb-98654.firebaseio.com")
.build();
FirebaseApp.initializeApp(options);
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("sameer");
DatabaseReference usersRef = ref.child("users");
Map<String, String> users = new HashMap<>();
users.put("HaiderAli", "HaiderAli");
users.put("sameer", "HaiderAli");
usersRef.setValueAsync(users);
System.out.println("Done");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
如果有人能解释 - 因为我没有收到任何错误并执行了来自 https://firebase.google.com/docs/database/admin/save-data 的相同步骤
最佳答案
您的程序在 SDK 完成写入之前终止。 setValueAsync
是异步的,因此它会在另一个线程完成写入时立即返回。这意味着主函数也立即返回。当您的 main 函数返回时,java 进程终止,并且异步写入永远不会完成。您需要做的是让您的程序等待写入完成。
setValueAsync返回 ApiFuture对象,它可以让您跟踪异步操作的结果。让程序等待 ApiFuture 完成的最简单方法可能是使用它的 get() 方法:
ApiFuture<Void> future = usersRef.setValueAsync(users);
future.get(10, TimeUnit.SECONDS); // wait up to 10s for the write to complete
在实际的生产代码中,您可能想要做一些更复杂的事情,例如听取 ApiFuture 的结果以继续您的代码或处理错误。
Read more about async operations with the Admin SDK in this blog .
关于java - 无法从 java admin sdk 将数据添加到 firebase 实时数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51045938/