【问题标题】:How to write data to firebase with a Java program如何使用 Java 程序将数据写入 Firebase
【发布时间】:2017-10-24 08:56:58
【问题描述】:

我正在尝试将数据写入现有的 Firebase 数据库,但没有写入数据。

是否有一个示例 Java 程序可以将数据写入某个地方的 Firebase 数据库,我可以使用吗?

到目前为止,我所做的如下:

package org.nilostep.bota.dcp.export;

import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.auth.FirebaseCredentials;
import com.google.firebase.database.*;

import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Map;

public class ReadWriteFirebase {

    private static final String DATABASE_URL = " (the url of my database) ";


    public static void main(String[] args) throws Exception {
    FileInputStream serviceAccount =
            new FileInputStream("bota-6e0b33e3f1fe.json");

    FirebaseOptions options = new FirebaseOptions.Builder().setCredential(FirebaseCredentials.fromCertificate(serviceAccount)).setDatabaseUrl("https://bota-313fb.firebaseio.com").build();

    FirebaseApp.initializeApp(options);

    DatabaseReference db = FirebaseDatabase.getInstance().getReference().child("testdata");

    Map<String, String> users = new HashMap<>();
    users.put("A", "Jaap");
    System.out.println(users);
    db.setValue(users);

    System.out.println(db);
}

}

'testdata' 是数据库根目录下的现有子项。

程序的第二个版本

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

    FileInputStream serviceAccount =
            new FileInputStream("bota-6e0b33e3f1fe.json");

    FirebaseOptions options = new FirebaseOptions.Builder()
            .setCredential(FirebaseCredentials.fromCertificate(serviceAccount))
            .setDatabaseUrl(DATABASE_URL)
            .build();

    FirebaseApp.initializeApp(options);

    FirebaseDatabase db = FirebaseDatabase.getInstance(DATABASE_URL);
    DatabaseReference ref = db.getReference().child("testdata");
    ref.setValueAsync("I'm writing data", 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.");
            }
        }
    });

它停止并显示以下消息:

Exception in thread "main" com.google.firebase.database.DatabaseException: Failed to parse node with class class org.nilostep.bota.dcp.export.ReadWriteFirebase$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:38)
at com.google.firebase.database.DatabaseReference.setValue(DatabaseReference.java:241)
at com.google.firebase.database.DatabaseReference.setValueAsync(DatabaseReference.java:218)
at org.nilostep.bota.dcp.export.ReadWriteFirebase.main(ReadWriteFirebase.java:44)

【问题讨论】:

  • 有什么问题?
  • 没有写入数据库。我还安装了github.com/pronto-it-labs/firebase-demo,这很容易安装。此应用可以运行,但也不写入 Firebase。
  • 请注意,您必须在 john-doe-ctrl.js、jane-doe-ctrl.js 和 FirebaseService.java 中替换您的 url
  • 您可以尝试在setValue() 调用中添加一个完成处理程序吗?请参阅:firebase.google.com/docs/database/admin/… 另一个线索:您使用的是哪个版本的 Firebase Admin SDK?
  • 管理员 SDK 5.4.0 : com.google.firebasefirebase-admin5.4.0 稍后再谈另一件事。谢谢,到目前为止。

标签: java firebase firebase-realtime-database


【解决方案1】:

注意

CountDownLatch,
latch.countdown(), 
latch.await()

没有记录。

以下课程有效。

import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.CountDownLatch;

public class Firebase {

    private static final String DATABASE_URL = "YOUR_DB_URL";
    private FirebaseDatabase firebaseDatabase;

    public Firebase() {
        InputStream serviceAccount = this.getClass().getResourceAsStream("/bota-6e0b33e3f1fe.json");

        try {
            FirebaseOptions options = new FirebaseOptions.Builder()
                .setCredentials(GoogleCredentials.fromStream(serviceAccount))
                .setDatabaseUrl(DATABASE_URL)
                .build();
            FirebaseApp.initializeApp(options);
            firebaseDatabase = FirebaseDatabase.getInstance(DATABASE_URL);

        } catch (IOException ioe) {
            System.out.println(ioe.getMessage());
        }
    }

    public void update(Object value) {
        update(value, "testdata");
    }

    public void update(Object value, String key) {
        try {
            DatabaseReference ref = firebaseDatabase.getReference(key);
            final CountDownLatch latch = new CountDownLatch(1);
            ref.setValue(value, new DatabaseReference.CompletionListener() {
                @Override
                public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
                    if (databaseError != null) {
                        System.out.println("Data could not be saved " + databaseError.getMessage());
                        latch.countDown();
                    } else {
                        System.out.println("Data saved successfully.");
                        latch.countDown();
                    }
                }
            });
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void close() {
        firebaseDatabase.getApp().delete();
    }
}

【讨论】:

    猜你喜欢
    • 2022-01-01
    • 2013-12-14
    • 1970-01-01
    • 2013-10-22
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多