Reputation: 447
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?
Upvotes: 8
Views: 17733
Reputation: 1
When you set a Value on Database since a Class as UserModel, only will be published those variables that you set public, and not private.
Private: null values Public : right Values
Upvotes: 0
Reputation: 8841
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);
}
Upvotes: 10