Ad

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 ?

Ad

Answer

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();
Ad
source: stackoverflow.com
Ad