i am trying to add data to firebase realtime database from a simple java program It executed properly as described in https://firebase.google.com/docs/database/admin/save-data
But i am not seeing data to firebase console - its not getting actually added to database
Code
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();
}
}
if anyone can explain - bcoz there isnt any error i am getting and executed same steps from https://firebase.google.com/docs/database/admin/save-data
Your program is terminating before the SDK can finish the write. setValueAsync
is asynchronous, so it returns immediately while the write finishes on another thread. This means that the main function also returns immediately. When your main function returns, the java process terminates, and the async write never completes. What you need to do is make your program wait until the write completes.
setValueAsync returns an ApiFuture object which lets you track the result of the async operation. Probably the easiest thing you can do to make your program wait for some time for the ApiFuture to complete is to use its get() method:
ApiFuture<Void> future = usersRef.setValueAsync(users);
future.get(10, TimeUnit.SECONDS); // wait up to 10s for the write to complete
In actual production code, you'll probably want to do something more sophisticated, such as listen to the results of the ApiFuture to continue your code or process errors.
Read more about async operations with the Admin SDK in this blog .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.