如何从firebase实时数据库中检索数据并使用JAVA将其保存在变量中

问题描述

我创建了一个 Web 应用程序,将用户数据发送到 Firebase 实时数据库。我尝试创建一个 Java 应用程序,它应该从 Firebase 获取数据并将它们保存在变量中。我已经创建了 2 个版本的表格,因为我有一个问题,对于我的目的来说,使用什么会更好? 首先是 firebase 数据(我保存了来自同一用户的相同数据):

enter image description here

现在是 JAVA 应用程序,我是 JAVA 和 firebase 的新手,所以我的知识很少。所以在我的代码中,它尝试从 Firebase Storage 获取用户名并将其保存在变量中,但我的代码不起作用。

import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.database.*;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;

public class getUserData {

public static void main(String[] args) throws IOException,InterruptedException {
    FileInputStream serviceAccount = new FileInputStream("myAPIKey");
    FirebaseOptions options = FirebaseOptions.builder()
            .setCredentials(GoogleCredentials.fromStream(serviceAccount))
            .setDatabaseUrl("https://myFirebaseStorage.firebaseio.com")
            .build();
    FirebaseApp.initializeApp(options);

    class users {
        public String Name;

    }
    final DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Name");
    CountDownLatch latch = new CountDownLatch(1);
    ref.orderByChild("Name").addChildEventListener(new ChildEventListener() {

        @Override
        public void onChildAdded(DataSnapshot dataSnapshot,String prevChildKey) {
            users user = dataSnapshot.getValue(users.class);
            System.out.println(dataSnapshot.getKey() + user.Name);
        }

        @Override
        public void onChildChanged(DataSnapshot dataSnapshot,String s) {

        }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {

        }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot,String s) {

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
    latch.await();
}}

我先谢谢大家。我希望这包含足够的信息。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)