Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Failed to convert value of type java.util.HashMap to String

I have no idea how i can render this JSON on logcat :enter image description here

The source code to get data from firebase realtime database :

FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("hotel");

myRef.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        String value = dataSnapshot.getValue(String.class);
        Log.d(TAG, "Value is: " + value);
    }

    @Override
    public void onCancelled(DatabaseError error) {
        Log.w(TAG, "Failed to read value.", error.toException());
    }
});

It says error like this :

com.google.firebase.database.DatabaseException: Failed to convert value of type java.util.HashMap to String

I've tried some tutorial, but i can't find one. Also, i try this :

HashMap value = DataSnapshot.getValue(HashMap.class);

It ended up error as well. How should i render this HashMap data ?

like image 721
Rido Avatar asked Dec 02 '22 11:12

Rido


1 Answers

You are getting HashMap of String as key and Object as Value so map it into something like below.

myRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
             Map<String, Object> map = (Map<String, Object>) dataSnapshot.getValue();
            Log.d(TAG, "Value is: " + map);
        }

        @Override
        public void onCancelled(DatabaseError error) {
            Log.w(TAG, "Failed to read value.", error.toException());
        }
    });

or we can get this parsed into some Model instead of an object.

update use this to parse

 Map<String, Object> map = (Map<String, Object>) dataSnapshot.getValue();
like image 80
vikas kumar Avatar answered Dec 04 '22 12:12

vikas kumar