dataSnapshot无法获取父推键值

时间:2020-10-11 01:22:51

标签: java android firebase firebase-realtime-database

我希望dataSnapshot检查其父级“摘要”中是否存在“月”。但是dataSnapshot返回的是“摘要”中没有“月”

 ds = FirebaseDatabase.getInstance().getReference("summary");
 ds.addListenerForSingleValueEvent(new ValueEventListener() {
                            @Override
                            public void onDataChange(DataSnapshot dataSnapshot) {
                                //summary
                                String key = ds.getKey();
                                if (dataSnapshot.hasChild("month")) {

                                    Toast.makeText(newTransaction.this, "got value", Toast.LENGTH_LONG).show();
                                } else {
                                    Toast.makeText(newTransaction.this, "No value", Toast.LENGTH_LONG).show();
                                }
                            }

我的Firebase数据库:我要检查其父级(红线)的值(蓝线)

My Firebase Database

1 个答案:

答案 0 :(得分:0)

以下代码行:

summary

返回引用所指向的节点的键,在这种情况下为summary。在month节点和summary属性之间,您的结构中还有另一个级别,实际上是该推键(-MJKC ... xGZX)。为了检查该属性是否存在,您还需要在引用中使用该键。假设DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference(); DatabaseReference keyRef = rootRef.child("summary").child("-MJKC_JkVFpCdCGqxGZX"); ValueEventListener valueEventListener = new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if (dataSnapshot.hasChild("month")) { Toast.makeText(newTransaction.this, "got value", Toast.LENGTH_LONG).show(); } else { Toast.makeText(newTransaction.this, "No value", Toast.LENGTH_LONG).show(); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors! } }; keyRef.addListenerForSingleValueEvent(valueEventListener); 节点是Firebase数据库根目录的直接节点,请使用以下代码行:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference summaryRef = rootRef.child("summary");
Query queryByMonth = summaryRef.orderByChild("month")
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if (dataSnapshot.exists()) {
            Toast.makeText(newTransaction.this, "got value", Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(newTransaction.this, "No value", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
    }
};
queryByMonth.addListenerForSingleValueEvent(valueEventListener);

但是,您尚未将该键存储到变量中,则应使用查询,如下所示:

{{1}}