如何从给定结构在Firebase Android中搜索数据

时间:2018-07-11 09:42:18

标签: android firebase firebase-realtime-database

我想像这样在Firebase中搜索数据:

enter image description here

我已经尝试过,但是没有用

 //Query query = FirebaseDatabase.getInstance().getReference(uid).orderByChild("title").startAt(editable.toString()).endAt(editable.toString()+"\uf888");

            DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("categoreis");
           Query query =  FirebaseDatabase.getInstance().getReference("categoreis").limitToFirst(4).orderByChild("image");
            query.addValueEventListener(new ValueEventListener() {

                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    list.clear();
               for (DataSnapshot data:dataSnapshot.getChildren())
               {

                   for (DataSnapshot ds:data.child("SubAccessories").getChildren())
                   {
                       for (DataSnapshot ds1:ds.getChildren())
                       {
                           //Log.d("checkData1",ds1.toString());

                           //Log.d("checkData1",ds1.child("image").getValue(String.class));

                       }
                   }

               }

1 个答案:

答案 0 :(得分:0)

如果您想获得我在问题中看到的image,请使用以下代码行,但假设categories节点是Firebase数据库根目录的直接子节点:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = rootRef.child("categories/Accessories/SubAccessories/Accessories/Grab Bar");
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        String image = dataSnapshot.child("image").getValue(String.class);
        Log.d("TAG", image);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
ref.addListenerForSingleValueEvent(valueEventListener);

根据您的评论,您应该使用Accessories这样的方法遍历第二个getChildren()节点:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = rootRef.child("categories/Accessories/SubAccessories/Accessories");
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String image = dataSnapshot.child("image").getValue(String.class);
            Log.d("TAG", image);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
ref.addListenerForSingleValueEvent(valueEventListener);