firebase / firebase-admin-java

Firebase Admin Java SDK
https://firebase.google.com/docs/admin/setup
Apache License 2.0
543 stars 269 forks source link

I cant save data from Java Class with Main Method #213

Closed ericciaparicio closed 5 years ago

ericciaparicio commented 6 years ago

Hello. I am trying to save data on Firebase Database Real Time from Java Class with Main Method.

The code is:

public class App {

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

    // Fetch the service account key JSON file contents
    FileInputStream serviceAccount = new FileInputStream("C:\\IDE\\workspace\\FirebaseDB\\myappnotif-841e1-firebase-adminsdk-dlzsd-6af0dae740.json");

    // Initialize the app with a service account, granting admin privileges
    FirebaseOptions options = new FirebaseOptions.Builder()
        .setCredentials(GoogleCredentials.fromStream(serviceAccount))
        .setDatabaseUrl("https://myappnotif-841e1.firebaseio.com/")             
        .build();
    FirebaseApp.initializeApp(options);             

    DatabaseReference ref = FirebaseDatabase.getInstance().getReference("blog");

    Map<String, User> users = new HashMap<>();

    User user = new User("juan");
    users.put("user", user);

    CountDownLatch done = new CountDownLatch(1);

    ref.child("users").setValueAsync(users, new DatabaseReference.CompletionListener() {
        @Override
        public void onComplete(DatabaseError de, DatabaseReference dr) {
            System.out.println("COMPLETEEEE");
            done.countDown();
        }
    });

    try {
        done.await();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

 }

}

This code throws this error:

  Exception in thread "main" com.google.firebase.database.DatabaseException: Failed to parse node 
 with 
  class class prueba.App$1
     at com.google.firebase.database.snapshot.NodeUtilities.NodeFromJSON(NodeUtilities.java:108)
     at com.google.firebase.database.snapshot.NodeUtilities.NodeFromJSON(NodeUtilities.java:33)
     at com.google.firebase.database.snapshot.PriorityUtilities.parsePriority(PriorityUtilities.java:43)
     at com.google.firebase.database.DatabaseReference.setValueAsync(DatabaseReference.java:216)
    at prueba.App.main(App.java:47)

Any suggest?

Regards

Emiliano

google-oss-bot commented 6 years ago

I found a few problems with this issue:

hiranya911 commented 5 years ago

2nd argument to setValueAsync() should be a json serializable priority value. You're passing in a CompletionListener which is wrong.