gpt4 book ai didi

java - 如何使用 Java 将数据保存到 Firebase(桌面)

转载 作者:行者123 更新时间:2023-11-30 02:12:12 25 4
gpt4 key购买 nike

我正在尝试使用用 Java 编写的桌面应用程序将数据保存到 Firebase。但是,由于某种原因它不起作用,我一直在遵循此处提供的文档:https://firebase.google.com/docs/database/admin/save-data 。找不到任何有关此事的视频教程,所有视频都与网络或移动设备相关。基本上我想创建一个名为 Venda 的对象,它有 3 个属性(ID、数据、valor),然后将其保存在 Firebase 上。谢谢!

主要方法如下:

public class Main {

public static void main(String[] args) throws IOException, InterruptedException {
System.out.println("--------- Begin of Output ---------");
Firebase firebase = new Firebase();
VendasCRUD venda = new VendasCRUD(firebase);
venda.createVenda(new Venda(0, "23/05/1993", 45.67));
System.out.println("----------- End of Output -----------");
}

}

Firebase 连接:

public class Firebase {

public Firebase() throws FileNotFoundException, IOException {
FileInputStream serviceAccount = new FileInputStream("C:\\Users\\Alex\\Documents\\NetBeansProjects\\SEMS\\src\\main\\java\\br\\com\\sems\\firebase\\sems-firebase.json");

FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
.setDatabaseUrl("https://sems-firebase.firebaseio.com/")
.build();

FirebaseApp.initializeApp(options);
}

public DatabaseReference getDataBaseReference() {
return FirebaseDatabase.getInstance().getReference();
}

}

文达级:

public class Venda {

public int ID;
public String data;
public double valor;

public Venda(int ID, String data, double valor) {
this.ID = ID;
this.data = data;
this.valor = valor;
}

@Override
public String toString() {
return ID + "," + data + "," + valor;
}

}

数据库信息:

enter image description here

目前,出于测试目的,规则设置为公开。

<小时/>

更新:

好吧,在尝试了 FrankvanPuffelen 评论中的建议后,我仍然无法从 Firebase 保存或读取数据。我出于测试目的编写了一个更简单的代码。这是代码:

public class Main {

private static final String DATABASE_URL = "https://sems-firebase.firebaseio.com/";
private static DatabaseReference database;
private static boolean finished = false;

public static void startListeners() {
database.child("posts").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Post post = dataSnapshot.getValue(Post.class);
System.out.println(post);
finished = true;
}

@Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
while(!finished);
}

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

try {
FileInputStream serviceAccount = new FileInputStream("sems-firebase.json");
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
.setDatabaseUrl(DATABASE_URL)
.build();



FirebaseApp defaultApp = FirebaseApp.initializeApp(options);
FirebaseDatabase defaultDatabase = FirebaseDatabase.getInstance(defaultApp);

System.out.println(defaultDatabase.getReference().toString());

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

// Start listening to the Database
startListeners();

}

}

所以我一直在做的是,我运行代码,然后转到数据库网址并手动编辑帖子,我希望得到我刚刚在控制台上编辑的帖子的打印,但没有任何反应。

这是数据库的快照: enter image description here

<小时/>

更新2

我相信这里提出的建议:Why Firebase Java SDK can't terminate after set?已弃用,因为如果我尝试代码如下所示:

enter image description here

我尝试将其修改为:

public static void startListeners() throws InterruptedException {
DatabaseReference database = FirebaseDatabase.getInstance().getReference("posts/adad2131/author");
CountDownLatch done = new CountDownLatch(1);
database.setValue("Test", new DatabaseReference.CompletionListener() {
@Override
public void onComplete(DatabaseError de, DatabaseReference dr) {
done.countDown();
}
});
done.await();
}

但是 onComplete 方法永远不会被执行,程序也永远不会完成。至于这里提出的建议:java Firebase: delay exit until writes finish也可能已被弃用,因为 CompletionListener() 似乎不再存在于 Firebase 中,但我可以在 DatabaseReference 中找到它,因此我将代码修改为:

private static final String DATABASE_URL = "https://sems-firebase.firebaseio.com/";

public static void startListeners() throws InterruptedException {
DatabaseReference database = FirebaseDatabase.getInstance().getReference("posts/adad2131/author");
final AtomicBoolean done = new AtomicBoolean(false);
database.setValue("Test", new DatabaseReference.CompletionListener() {
@Override
public void onComplete(DatabaseError de, DatabaseReference dr) {
done.set(true);
}
});
while (!done.get());
}

像以前一样,onComplete 方法永远不会被执行,程序也永远不会完成或在数据库中设置数据。这是我尝试修改的帖子的快照:

enter image description here

<小时/>

更新3

所以我简化了代码以方便使用。为了确保我从项目的服务帐户面板生成了新的私钥,以下是我初始化应用程序的方法:

    try {
FileInputStream serviceAccount = new FileInputStream("sems-firebase-firebase-adminsdk-gamnp-874087bbd1.json");
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
.setDatabaseUrl("https://sems-firebase.firebaseio.com/")
.build();

FirebaseApp.initializeApp(options);

} catch (IOException e) {
System.out.println("ERROR: invalid service account credentials.");
System.out.println(e.getMessage());

System.exit(1);
}

这是数据库的快照,我试图更改的值是 ID 为“adad2131”的帖子的作者字段。

enter image description here

我尝试使用“posts/adad2131/author”、“/posts/adad2131/author”或简单的“adad2131/author”引用该字段,也许我引用错了?

完整代码如下:

public class Main {

public static void main(String[] args) throws FileNotFoundException, InterruptedException {

try {
FileInputStream serviceAccount = new FileInputStream("sems-firebase-firebase-adminsdk-gamnp-874087bbd1.json");
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
.setDatabaseUrl("https://sems-firebase.firebaseio.com/")
.build();

FirebaseApp.initializeApp(options);

} catch (IOException e) {
System.out.println("ERROR: invalid service account credentials.");
System.out.println(e.getMessage());

System.exit(1);
}

//Try to change data in Firebase
CountDownLatch done = new CountDownLatch(1);
FirebaseDatabase.getInstance().getReference("posts/adad2131/author").setValue("Test", new DatabaseReference.CompletionListener() {
@Override
public void onComplete(DatabaseError de, DatabaseReference dr) {
done.countDown();
}
});
done.await();

}
}

诗。我也在使用 admin sdk 5.9

最佳答案

我刚刚使用 Firebase Admin SDK 5.9 将您的代码复制到项目中并运行它,它写入数据库时​​没有出现任何问题。

CountDownLatch done = new CountDownLatch(1);
FirebaseDatabase.getInstance().getReference("49723347").setValue("Test", new DatabaseReference.CompletionListener() {
@Override
public void onComplete(DatabaseError de, DatabaseReference dr) {
done.countDown();
}
});
done.await();

您可以在此处查看结果:https://stackoverflow.firebaseio.com/49723347.json

引用49723347是我数据库中的路径(它是您的问题的ID)。我没有做任何其他更改。

看来问题不在我们一直在查看的代码中。以下是我初始化应用程序的方法:

FileInputStream serviceAccount = new FileInputStream("stackoverflow-3d9889aaeddb.json");

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

FirebaseApp.initializeApp(options);

您确定该配置适合您要编写的项目吗?

关于java - 如何使用 Java 将数据保存到 Firebase(桌面),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49723347/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com