Search code examples
androidandroid-fragmentsandroid-viewmodel

How to use HashMap in ModelView?


I try to use a ViewModel for the first time and there is an error that I cannot resolve. I get the message "Cannot resolve put", how do I resolve this problem?

public class SharedViewModel extends ViewModel {

public HashMap<Integer, MutableLiveData<String>> answers = new HashMap<Integer, MutableLiveData<String>>(){
            answers.put(1, new MutableLiveData<String>())
            answers.put(2, new MutableLiveData<String>())
            answers.put(3, new MutableLiveData<String>())
};



public MutableLiveData<String> getAnswer(int questionId) {
    return answers.get(questionId);
}

public void setAnswer(int questionId, String answer) {
    if (answers.get(questionId) != null) {
        answers.get(questionId).setValue(answer);
    }
}
}

Solution

  • Instead of this

    public HashMap<Integer, MutableLiveData<String>> answers = new HashMap<Integer, MutableLiveData<String>>(){
            answers.put(1, new MutableLiveData<String>())
            answers.put(2, new MutableLiveData<String>())
            answers.put(3, new MutableLiveData<String>())
    };
    

    Do this

    public HashMap<Integer, MutableLiveData<String>> answers = new HashMap<Integer, MutableLiveData<String>>(){{
            put(1, new MutableLiveData<String>())
            put(2, new MutableLiveData<String>())
            put(3, new MutableLiveData<String>())
    }};