如何从Firebase实时数据库读取数据

huangapple go评论73阅读模式
英文:

How to read data from the Firebase realtime database

问题

我想从 Firebase 实时数据库中的特定节点读取数据。
这是我的 JSON 树:

{
  "user": "1",
  "user_details": {
    "emails": ["valker@gmail.com"],
    "usernames": ["valk stone"]
  }
}

我如何从 user 节点读取数据?

英文:

I want to read data from a particular node from the firebase realtime database.
This is my JSON tree:

{
  "user" : "1",
  "user_details" : {
    "emails" : [ "valker@gmail.com" ],
    "usernames" : [ "valk stone" ]
  }
}

How do I read data from the user node?

答案1

得分: 1

你可以通过监听器来读取数据。如果你阅读文档,你会了解到 SingleValueEvent 用于一次性读取数据:

ValueEventListener userListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        Log.d(dataSnapshot);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        // 获取数据失败,记录信息
        Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
        // ...
    }
};
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("user_details");
usersRef.addListenerForSingleValueEvent(userListener);
英文:

You can read data with the help of listener. If you read docs you come to know that SingleValueEventis used for read data once :

ValueEventListener userListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        Log.d(dataSnapshot);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        // Getting Post failed, log a message
        Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
        // ...
    }
};
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("user_details");
usersRef.addListenerForSingleValueEvent(userListener);

huangapple
  • 本文由 发表于 2020年9月18日 18:44:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/63954239.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定