如何使用Java(桌面)将数据保存到Firebase [英] How to save data to Firebase using Java (Desktop)

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

问题描述

我正在尝试使用Java编写的桌面应用程序将数据保存到Firebase.但是,由于某种原因它不起作用,我一直在这里查看提供的文档:

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


更新:

尝试了FrankvanPuffelen的评论后,我仍然无法保存或读取Firebase中的数据.我为测试目的编写了一个更简单的代码.这是代码:

 公共类Main {私有静态最终字符串DATABASE_URL ="https://sems-firebase.firebaseio.com/";私有静态DatabaseReference数据库;私人静态布尔完成=假;公共静态无效startListeners(){database.child("posts").addValueEventListener(new ValueEventListener(){@Override公共无效onDataChange(DataSnapshot dataSnapshot){发布post = dataSnapshot.getValue(Post.class);System.out.println(post);完成=真;}@Override公共无效onCancelled(DatabaseError databaseError){System.out.println(读取失败:" + databaseError.getCode());}});while(!完成);}公共静态void main(String [] args)抛出FileNotFoundException {尝试 {FileInputStream serviceAccount = new FileInputStream("sems-firebase.json");FirebaseOptions选项=新的FirebaseOptions.Builder().setCredentials(GoogleCredentials.fromStream(serviceAccount)).setDatabaseUrl(DATABASE_URL).建造();FirebaseApp defaultApp = FirebaseApp.initializeApp(options);FirebaseDatabase defaultDatabase = FirebaseDatabase.getInstance(defaultApp);System.out.println(defaultDatabase.getReference().toString());} catch(IOException e){System.out.println(错误:无效的服务帐户凭据.请参阅自述文件.");System.out.println(e.getMessage());System.exit(1);}//共享数据库参考数据库= FirebaseDatabase.getInstance().getReference();//开始监听数据库startListeners();} 

}

所以我一直在做的是,我运行代码,然后转到数据库url并手动编辑帖子,我希望得到我刚刚在控制台上编辑过的帖子的打印件,但是什么也没发生./p>

这是数据库的快照:


更新2

我相信这里提出的建议:

我试图对此进行修改:

 公共静态void startListeners()抛出InterruptedException {DatabaseReference数据库= FirebaseDatabase.getInstance().getReference("posts/adad2131/author");CountDownLatch完成=新的CountDownLatch(1);database.setValue("Test",新的DatabaseReference.CompletionListener(){@Override公共无效onComplete(DatabaseError de,DatabaseReference dr){done.countDown();}});done.await();} 

但是onComplete方法永远不会执行,程序永远也不会完成.至于这里提出的建议:


更新3

因此,我已简化代码以简化使用.为了确保我从项目的服务帐户面板中生成了一个新的私钥,这是我初始化应用程序的方式:

 尝试{FileInputStream serviceAccount = new FileInputStream("sems-firebase-firebase-adminsdk-gamnp-874087bbd1.json");FirebaseOptions选项=新的FirebaseOptions.Builder().setCredentials(GoogleCredentials.fromStream(serviceAccount)).setDatabaseUrl("https://sems-firebase.firebaseio.com/").建造();FirebaseApp.initializeApp(options);} catch(IOException e){System.out.println(错误:无效的服务帐户凭据.");System.out.println(e.getMessage());System.exit(1);} 

这是数据库的快照,我要更改的值是ID为"adad2131"的帖子的author字段.

我尝试使用"posts/adad2131/author","/posts/adad2131/author"或只是"adad2131/author"引用该字段,也许我在引用错误吗?

这是完整的代码:

 公共类Main {公共静态void main(String [] args)抛出FileNotFoundException,InterruptedException {尝试 {FileInputStream serviceAccount = new FileInputStream("sems-firebase-firebase-adminsdk-gamnp-874087bbd1.json");FirebaseOptions选项=新的FirebaseOptions.Builder().setCredentials(GoogleCredentials.fromStream(serviceAccount)).setDatabaseUrl("https://sems-firebase.firebaseio.com/").建造();FirebaseApp.initializeApp(options);} catch(IOException e){System.out.println(错误:无效的服务帐户凭据.");System.out.println(e.getMessage());System.exit(1);}//尝试更改Firebase中的数据CountDownLatch完成=新的CountDownLatch(1);FirebaseDatabase.getInstance().getReference("posts/adad2131/author").setValue("Test",新的DatabaseReference.CompletionListener(){@Override公共无效onComplete(DatabaseError de,DatabaseReference dr){done.countDown();}});done.await();}} 

Ps.我也在使用admin sdk 5.9

解决方案

我刚刚使用Firebase Admin SDK 5.9将您的代码复制到了一个项目中并运行了该代码,然后将其毫无问题地写入了数据库.

  CountDownLatch完成=新的CountDownLatch(1);FirebaseDatabase.getInstance().getReference("49723347").setValue("Test",新的DatabaseReference.CompletionListener(){@Override公共无效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选项=新的FirebaseOptions.Builder().setCredential(FirebaseCredentials.fromCertificate(serviceAccount)).setDatabaseUrl("https://stackoverflow.firebaseio.com/").建造();FirebaseApp.initializeApp(options); 

您确定配置是针对您要编写的项目的吗?

I'm trying to save data to Firebase using a desktop application written in Java. However, for some reason it doesn't work, I've been folowing the documentation provided here: https://firebase.google.com/docs/database/admin/save-data. Couldn't find any video tutorials on the matter, all videos are web or mobile related. Basically I want to create an object called Venda that has 3 attributes (ID, data, valor) and then save it on Firebase. Thank you!

Here is the main method:

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 connection:

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

}

Venda class:

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

}

The database info:

For now the rules are set to public, for testing purposes.


UPDATE:

Alright after trying what was proposed on FrankvanPuffelen's comment I'm still not able to save or read data from Firebase. I made a simpler code for testing purposes. Here is the code:

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

}

}

So what I've been doing is, I run the code and then go to the database url and manually edit a post, I expect to get a print of the post I just edited on the console, but nothing happens.

Here is a snapshot of the database:


UPDATE 2

I believe what was proposed here: Why Firebase Java SDK can't terminate after set? is deprecated, because if I try the code looks like this:

I tried modifying that to this:

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

But the onComplete method never gets executed and the programs never finishes. As for what was proposed here: java Firebase: delay exit until writes finish may also be deprecated as it seems the CompletionListener() no longer lives inside Firebase, but I could find it inside DatabaseReference, so I modified the code to this:

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

Like before, the onComplete method never gets executed and the program never finishes or set the data in the database. Here is a snapshot of the post I'm trying to modify:


UPDATE 3

So I've simplified the code for ease of use. Just to be sure I generated a new private key from the project's service account pannel, here is how I initialize the app:

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

Here is a snapshot of the database, the value I'm trying to change is the author field of post with id "adad2131".

I've tried referencing that field with "posts/adad2131/author", "/posts/adad2131/author" or simply "adad2131/author", maybe I'm referencing it wrong?

Here is the full code:

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

    }
}

Ps. I'm also using admin sdk 5.9

解决方案

I just copied your code into a project using Firebase Admin SDK 5.9 and ran it, and it wrote to the database without problems.

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

You can see the result here: https://stackoverflow.firebaseio.com/49723347.json

The reference 49723347 is the path in my database (it's the ID of your question). I made no other changes.

So it seems that the problem is not in the code we've been looking at. Here's how I initialize the app:

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

Are you sure the configuration is for the project you're trying to write?

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

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