首页 > 解决方案 > 我想将 Netbeans java 应用程序与 Firebase 数据库连接起来

问题描述

我是 Firebase 的新手。我知道有一个 SDK(Firebase Admin SDK)允许您将 Java 应用程序连接到 Firebase 数据库。我遵循了 Firebase 网站 ( https://firebase.google.com/docs/database/admin/start ) 上给出的所有说明,但我的数据仍然没有保存在数据库中。我的代码如下:

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);
    }


}
}

我的 build.gradle 文件如下:

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'
}

请帮帮我。

标签: javafirebasenetbeansfirebase-admin

解决方案


Firebase SDK 与其服务器之间的所有交互都在辅助线程上异步发生。这意味着 JVM 很可能在该线程有机会将数据发送到数据库之前退出。为了防止这种情况发生,您需要让主线程等待对数据库的写入完成。

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();

另见:


推荐阅读