Daniel Spatz
Daniel Spatz

Reputation: 87

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);
    }
}
}

Upvotes: 0

Views: 2329

Answers (2)

Rajnish suryavanshi
Rajnish suryavanshi

Reputation: 3424

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>())
}};

Upvotes: 2

Kishan Maurya
Kishan Maurya

Reputation: 3394

public HashMap<Integer, MutableLiveData<String>> answers = new HashMap<Integer, MutableLiveData<String>>();

    public void initValues(){
        answers.put(1, new MutableLiveData<String>())
        answers.put(2, new MutableLiveData<String>())
        answers.put(3, new MutableLiveData<String>())
    }

call this method init from fragment/activity

or try 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>());
        }
    };

Upvotes: 0

Related Questions