Java应用程序将数据推送到Firebase

时间:2018-03-10 15:37:10

标签: java firebase firebase-realtime-database firebase-admin

我正在尝试构建java应用程序以检索并将数据保存到Firebase数据库。 我已经关注this link并下载了服务帐户详细信息,并在项目中使用了相同的内容。我正在IntelliJ上构建一个项目,并添加了所需的所有依赖项。但是我无法从firebase中保存/检索任何数据。 在运行代码时,我没有收到任何错误。

public class Database {
private static final String DATABASE_URL = "https://DATABASE-NAME.firebaseio.com";
private static final String FILE_NAME = "services-account-downloaded-file.json";
private static DatabaseReference database;

public static void main(String args[]) {
    // Initialize Firebase
    try {
        // [START initialize]
        FileInputStream serviceAccount = new FileInputStream(FILE_NAME);

        FirebaseOptions options = new FirebaseOptions.Builder()
                .setCredential(FirebaseCredentials.fromCertificate(serviceAccount))
                .setDatabaseUrl(DATABASE_URL)
                .setDatabaseAuthVariableOverride(null)
                .build();
        FirebaseApp.initializeApp(options);
        // [END initialize]
    } catch (IOException e) {
        System.out.println("ERROR: invalid service account credentials. See README.");
        System.out.println(e.getMessage());

        System.exit(1);
    }
    // Shared Database reference
    database = FirebaseDatabase.getInstance().getReference();
    startListeners();
    try {
        Thread.sleep(20000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

public static void startListeners() {
    FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference ref = database.getReference().child("user");
    ref.setValue("userdata", 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.");
            }
        }
    });
}

}

1 个答案:

答案 0 :(得分:0)

需要注意的是:FirebaseCredential已被弃用,转而使用GoogleCredentials。

尝试将初始化块更改为:

objects