Issue
At this line of my code in my OnDataChange()
method in the ValueEvenListener
:
int latest = dataSnapshot.getValue(Integer.class);
I'm getting a DatabaseException
with the error Failed to convert a value of type java.util.HashMap to int
.
However, in my database, you can take a look at the image below:
It is obviously not a HashMap
but an int
. Is this a bug or am I doing something wrong? What can I do to fix it? Why is it retrieving a Hashmap
when the value is int
?
Full dataSnapshot:
final DatabaseReference database = FirebaseDatabase.getInstance().getReference();
database.child("Campaigns").child(key).child("count");
database.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
int latest = dataSnapshot.getValue(Integer.class);
button.setText(latest + "");
}
@Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(context, context.getString(R.string.error) + ": " + databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
Database:
Campaigns:{
-JDKKDJIIDJFIDJKDK:{
count:2432
}
}
Solution
It turns out I had to child dataSnapshot to my destination again. E.g:
int latest = dataSnapshot.child("Campaigns").child(key).child("count").getValue(Integer.class);
By default dataSnapshot
is actually my whole database.
Answered By - Ali Bdeir
Answer Checked By - Pedro (JavaFixing Volunteer)