Firebase “Failed to convert a value of type java.util.HashMap to int”

后端 未结 3 1658
半阙折子戏
半阙折子戏 2021-01-21 17:05

At this line of my code in my OnDataChange() method in the ValueEvenListener:

int latest = dataSnapshot.getValue(Integer.class);


        
相关标签:
3条回答
  • 2021-01-21 17:51

    This should work if we assume that the dataSnapshot is right.

    final DatabaseReference database = FirebaseDatabase.getInstance().getReference();
    database = database.child("Campaigns").child(key).child("count"); // replaced
    
            database.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    int latest = Integer.valueOf(dataSnapshot.getValue().toString()); // replaced
                    button.setText(latest + "");
                }
    
                @Override
            public void onCancelled(DatabaseError databaseError) {
                Toast.makeText(context, context.getString(R.string.error) + ": " + databaseError.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    

    Reminder : addValueEventListener will run everytime there is a change in the dataSnapshot. If you want to run it just once use addListenerForSingleValueEvent instead.

    0 讨论(0)
  • 2021-01-21 17:54

    Your ValueEventListener is attached to the whole database.

    // This line gets a reference to the whole database
    final DatabaseReference database =  FirebaseDatabase.getInstance().getReference();
    
    // This line creates a child DatabaseReference, but you don't assign
    // the child to a variable
    database.child("Campaigns").child(key).child("count");
    
    // This line adds a ValueEventListener to the whole database
    database.addValueEventListener(new ValueEventListener() {
    

    What you want instead is this:

    final DatabaseReference database = FirebaseDatabase.getInstance().getReference()
    final DatabaseReference countRef = database.child("Campaigns").child(key).child("count")
    countRef.addValueEventListener(new ValueEventListener() {
        // ...
    });
    

    You can see that in the latter example the ValueEventListener is attached to the child reference, not to the root.

    0 讨论(0)
  • 2021-01-21 18:11

    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.

    0 讨论(0)
提交回复
热议问题