Android Firebase数据库 - 检索数据

时间:2018-02-28 04:15:40

标签: android firebase firebase-realtime-database

我正在开发一款使用Firebase数据库的Android应用。

"posts": [
    {
      "post_id": 100,
      "post_kind": "V"
    },
    {
      "post_id": 100,
      "post_kind": "S"
    },
    {
      "post_id": 100,
      "post_kind": "S"
    }
]

我想查询选择post_kind = S

的所有帖子

我正在使用查询

databaseReference = firebaseDatabase.getReference("posts");
query = databaseReference.orderByChild("post_kind").equalTo("S");
query.addListenerForSingleValueEvent(new ValueEventListener() {
      @Override
      public void onDataChange(DataSnapshot dataSnapshot) {
          if (dataSnapshot.exists()) {
                    List<Post> list = new ArrayList<>();
                    for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                        Post post = (Post) snapshot.getValue(Post.class);
                        list.add(post);
                    }
                }
            }

     @Override
     public void onCancelled(DatabaseError databaseError) {
           Log.e("DatabaseError", databaseError.toString());
     }
});

但不是结果

2 个答案:

答案 0 :(得分:2)

试试这个。

<dependency>
    <groupId>com.mchange</groupId>
    <artifactId>mchange-commons-java</artifactId>
    <version>0.2.11</version>
</dependency>

答案 1 :(得分:0)

要解决此问题,请使用以下代码:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef.child("posts").orderByChild("post_kind").equalTo("S");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        List<Post> list = new ArrayList<>();

        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            Post post = ds.getValue(Post.class);
            list.add(post);
        }

        Log.d("TAG", list.toString);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        Log.e("DatabaseError", databaseError.toString());
    }
};
query.addListenerForSingleValueEvent(eventListener);