如何使用Java程序将数据写入Firebase [英] How to write data to firebase with a Java program

查看:85
本文介绍了如何使用Java程序将数据写入Firebase的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将数据写入现有的Firebase数据库,但未写入任何数据.

I am trying to write data to an existing Firebase database but no data is written.

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

Is there an example Java program that writes data to a Firebase database somewhere, that I can use?

我做过的事情如下:

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"是数据库根目录下的现有子级.

'testdata' is an existing child under the database root.

第二版程序

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

它停止并显示以下消息:

it stops with the following message:

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)

推荐答案

请注意

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

这篇关于如何使用Java程序将数据写入Firebase的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆