尝试合并orderByChild()和startAt()时使用null值

时间:2018-11-01 12:31:08

标签: java android firebase firebase-realtime-database

尝试使用以下代码使用OrderByChild()和startAt()排序和过滤数据时,将Value设置为null

我在下面附加图像,以数据快照的形式获取数据结构和结果。

enter image description here enter image description here

遵循的代码

Query queryMeal = FirebaseDatabase.getInstance().getReference("meals");
            queryMeal.orderByChild("meal_name").startAt("ggh").addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    Log.e("Query DataSnapShot",""+dataSnapshot.toString());
                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {

                }
            });

2 个答案:

答案 0 :(得分:1)

要解决此问题,请更改以下代码行:

Query queryMeal = FirebaseDatabase.getInstance().getReference("meals");
ueryMeal.orderByChild("meal_name").startAt("ggh").addListenerForSingleValueEvent();

String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
Query queryMeal = FirebaseDatabase.getInstance().getReference().child("meals").child(uid);
ueryMeal.orderByChild("meal_name").startAt("ggh").endAt("ggh" + "\uf8ff").addListenerForSingleValueEvent();

编辑:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference mealsRef = rootRef.child("meals");
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot uidSnapshot : dataSnapshot.getChildren()) {
            String uid = uidSnapshot.getKey();

            DatabaseReference uidRef = rootRef.child("meals").child(uid).startAt("ggh").endAt("ggh" + "\uf8ff");
            ValueEventListener eventListener = new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    for(DataSnapshot ds : dataSnapshot.getChildren()) {
                        String mealName = ds.child("meal_name").getValue(String.class);
                        Log.d(TAG, mealName);
                    }
                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {
                    Log.d(TAG, databaseError.getMessage());
                }
            };
            uidRef.addListenerForSingleValueEvent(eventListener);
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.d(TAG, databaseError.getMessage());
    }
};
mealsRef.addListenerForSingleValueEvent(valueEventListener);

答案 1 :(得分:0)

在您的onDataChange方法中执行以下操作

if(dataSnapshot != null){
   Log.e("Query DataSnapShot",""+dataSnapshot.getValue().toString());
}