8

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?

2
  • Use the debugger and you will know. Commented Aug 21, 2017 at 11:16
  • you cannot simple change using type casting use contsructor to add dynamicaly Commented Aug 21, 2017 at 11:22

2 Answers 2

10

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

I have tried this before and received a userModel with username & password = null. Here is my data when I call dataSnapshot.getValue() {id1={password=1234, userName=abcd}, id2={password=5678, userName=cde}}
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.