Search code examples
androidsharedpreferencesischecked

Android CheckBox isChecked() or editing SharedPreferences causing forced close


I'm writing a flash card app in Android, and I tried to add the ability to add a word to a review list by having a checkbox. When the user goes to the next word, I see whether the checkbox is checked. If it is, I add the word to the review list, and if it isn't, I remove the word. When I tested it on my phone and the emulator, I got a forced close every time I try to go to the next word or to the home page when the checkbox is checked. I don't know what's causing the error because in the LogCat page, it doesn't show the line number or what error happened.

I can flip through the words without a problem when I don't have them checked; checking it and going to another word is what causes a problem, so I'm guessing it has to do with the SharedPreferences.

Here are the important methods I have:

public void onCreate(Bundle savedInstanceState)
{
            //other code
    reviewCheckBox = (CheckBox) findViewById(R.id.reviewCheckBox);
    prefs = getPreferences(MODE_PRIVATE);
    editor = prefs.edit();
    reviewCards = prefs.getAll().keySet();
}
public void home(View v)
{
    if (flashCardPage.getVisibility() == View.VISIBLE)
    {
        if (reviewCheckBox.isChecked())
            reviewCards.add(currentCard.getTerm());
        else
            reviewCards.remove(currentCard.getTerm());

        updateReviewCards();
    }
    //other code
}
public void nextWord(View v)
{
    currentPosition++;

    if (currentPosition == flashCards.size())
    {
        home(wordTV);
    }
    else
    {
        if (reviewCheckBox.isChecked())
            reviewCards.add(currentCard.getTerm());
        else
            reviewCards.remove(currentCard.getTerm());

        //other code

        if (reviewCards.contains(currentCard.getTerm()))
            reviewCheckBox.setChecked(true);
        else
            reviewCheckBox.setChecked(false);
    }
}

public void previousWord(View v)
{
    if (currentPosition > 0)
    {
        if (reviewCheckBox.isChecked())
            reviewCards.add(currentCard.getTerm());
        else
            reviewCards.remove(currentCard.getTerm());

        //other code

        if (reviewCards.contains(currentCard.getTerm()))
            reviewCheckBox.setChecked(true);
        else
            reviewCheckBox.setChecked(false);
    }
}
public void updateReviewCards()
{
    editor.clear();

    for (String card : reviewCards)
        editor.putString(card, card);

    editor.commit();
}

Solution

  • The set returned by getPreferences().getAll().keySet() does not support adding.