Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.util.HashMap cannot be cast to Object

This is my class UserModel

public class UserModel {

private String userName;
private String password;

public UserModel(String userName, String password) {
    this.userName = userName;
    this.password = password;
}

public String getUserName() {
    return userName;
}

public String getPassword() {
    return password;
}
}

This is my way to get data from firebase

userReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            HashMap<String, UserModel> userModelHashMap = (HashMap<String, UserModel>) dataSnapshot.getValue();
            ArrayList<UserModel> userModelList = new ArrayList<>(userModelHashMap.values());
            if (userModelList.size() != 0) {
                Log.d(TAG, "onDataChange: " + userModelList.get(0));
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

It logs successfully.

onDataChange: {password=abcde, userName=1234}

Everything seems to be ok until I want to log more detail

Log.d(TAG, "onDataChange: " + userModelList.get(0).getUserName());

And here is the error of this line after I change my code

java.lang.ClassCastException: java.util.HashMap cannot be cast to qklahpita.vn.testfirebasedemo.UserModel

I cannot understand why getUserName() get wrong. If userModelList.get(0) do not return UserModel, what does it return?

like image 954
Qk Lahpita Avatar asked Aug 21 '17 11:08

Qk Lahpita


1 Answers

It is because the data you are getting is in the form of 'HashMap' and not 'UserModel'.You can do this to create objects instead.

UserModel userModel = dataSnapshot.getValue(UserModel.class);

Edit : You also need to loop through children if there are multiple users. Like this.

for(Datasnapshot userSnapshot : dataSnapsot.getChildren(){
   UserModel userModel = userSnapshot.getValue(UserModel.class);
}
like image 178
Dishonered Avatar answered Oct 14 '22 02:10

Dishonered