如何使用Java程序将数据写入firebase

时间:2017-10-24 08:56:59

标签: java firebase firebase-realtime-database

我正在尝试将数据写入现有的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)

1 个答案:

答案 0 :(得分:4)

注意

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