-1

I am new to Firebase. I know there is an SDK (Firebase Admin SDK) which allows you to connect a Java application to the Firebase Database. I followed all the instructions given on the Firebase's website ( https://firebase.google.com/docs/database/admin/start ) but still my data is not getting saved in the database. My code is as follows :

import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Map;

public class FirebaseDBDemo {

public String date_of_birth;
public String full_name;
public String nickname;

public FirebaseDBDemo(String date_of_birth, String full_name) {
    this.date_of_birth = date_of_birth;
    this.full_name = full_name;
}

public FirebaseDBDemo(String date_of_birth, String full_name, String nickname) {
    this.date_of_birth = date_of_birth;
    this.full_name = full_name;
    this.nickname = nickname;
}


public static void main(String[] args) {

    try {

        // Initializing the SDK

        FileInputStream serviceAccount = new FileInputStream("C:\\Users\\ABC\\Documents\\NetBeansFirebase\\New\\nbfb-51117-firebase-adminsdk-s2gs4-5b1a87c6b2.json");

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

        FirebaseApp.initializeApp(options);



        System.out.println("\n------SDK is Initialized------");



        final FirebaseDatabase database = FirebaseDatabase.getInstance();
        DatabaseReference ref = database.getReference("server/saving-data/fireblog");

        DatabaseReference usersRef = ref.child("users");
        Map<String, FirebaseDBDemo> users = new HashMap<>();
        users.put("alanisawesome", new FirebaseDBDemo("June 23, 1912", "Alan Turing"));
        users.put("gracehop", new FirebaseDBDemo("December 9, 1906", "Grace Hopper"));

        usersRef.setValueAsync(users);


    } catch (Exception e) {
        System.out.println(""+e);
    }


}
}

My build.gradle file is as follows :

apply plugin: 'java'

sourceCompatibility = '1.8'
[compileJava, compileTestJava]*.options*.encoding = 'UTF-8'

// NetBeans will automatically add "run" and "debug" tasks relying on the
// "mainClass" property. You may however define the property prior executing
// tasks by passing a "-PmainClass=<QUALIFIED_CLASS_NAME>" argument.

// Note however, that you may define your own "run" and "debug" task if you
// prefer. In this case NetBeans will not add these tasks but you may rely on
// your own implementation.
if (!hasProperty('mainClass')) {
    ext.mainClass = 'FirebaseDBDemo'
}

repositories {
    mavenCentral()
    // You may define additional repositories, or even remove "mavenCentral()".
    // Read more about repositories here:

}

dependencies {
    // TODO: Add dependencies here ...
    // You can read more about how to add dependency here:

    testCompile group: 'junit', name: 'junit', version: '4.10'
    implementation 'com.google.firebase:firebase-admin:6.5.0'
    implementation 'org.slf4j:slf4j-jdk14:1.7.25'
}

Please help me out.

1 Answers1

0

All interaction between the Firebase SDK and its servers happens asynchronously on a secondary thread. This means the JVM most likely exits before that thread has had a chance to send the data to the database. To prevent that from happening, you'll need to make the main thread wait for the write to the database to complete.

final CountDownLatch sync = new CountDownLatch(1);
ref.push().setValue("new value")
   .addOnCompleteListener(new DatabaseReference. CompletionListener() {
     @Override
     public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
       if (databaseError != null) {
         System.out.println("Data could not be saved " + databaseError.getMessage());
       } else {
         System.out.println("Data saved successfully.");
       }
       sync.countDown();
     }
});
sync.await();

Also see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807