Datasnapshot Could Not Get Parent Push Key Value
I want dataSnapshot to check if 'month' exists in its parent's 'summary'. But dataSnapshot is returning that it does not have 'month' in 'summary' ds = FirebaseDatabase.getInstanc
Solution 1:
The following line of code:
Stringkey = ds.getKey();
Returns the key of the node on which the reference is pointing to, in this case summary
. Between the summary
node and the month
property, there is another level in your structure, which actually is that pushed key (-MJKC ... xGZX). In order to check if that property exists, you need to use that key in the reference too. Assuming that the summary
node is a direct node of your Firebase database root, please use the following lines of code:
DatabaseReferencerootRef= FirebaseDatabase.getInstance().getReference();
DatabaseReferencekeyRef= rootRef.child("summary").child("-MJKC_JkVFpCdCGqxGZX");
ValueEventListenervalueEventListener=newValueEventListener() {
@OverridepublicvoidonDataChange(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();
}
}
@OverridepublicvoidonCancelled(@NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
}
};
keyRef.addListenerForSingleValueEvent(valueEventListener);
However, you haven't store that key into a variable, then you should use a query, as below:
DatabaseReferencerootRef= FirebaseDatabase.getInstance().getReference();
DatabaseReferencesummaryRef= rootRef.child("summary");
QueryqueryByMonth= summaryRef.orderByChild("month")
ValueEventListenervalueEventListener=newValueEventListener() {
@OverridepublicvoidonDataChange(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();
}
}
@OverridepublicvoidonCancelled(@NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
}
};
queryByMonth.addListenerForSingleValueEvent(valueEventListener);
Post a Comment for "Datasnapshot Could Not Get Parent Push Key Value"