android – Programmatically populating preferences with checkboxes-ThrowExceptions

Exception or error:

In my setting page I have a preference which fetches a list of toggle-able settings that I wanted to display as individual checkbox preferences.

I know that preferences.xml supports generating lists of preferences (looking at wi-fi settings page) but ListPreference only allows you to select one from the list.

I’ve been searching for how to generate preferences programmatically but have only managed to find how to change attributes of preferences that are already in the XML.

How to solve:

Here is a short example (assuming you are extending PreferenceActivity):

public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    PreferenceScreen screen = getPreferenceManager().createPreferenceScreen(this);

    PreferenceCategory category = new PreferenceCategory(this);
    category.setTitle("category name");

    screen.addPreference(category);

    CheckBoxPreference checkBoxPref = new CheckBoxPreference(this);
    checkBoxPref.setTitle("title");
    checkBoxPref.setSummary("summary");
    checkBoxPref.setChecked(true);

    category.addPreference(checkBoxPref);
    setPreferenceScreen(screen);
}

###

Programatically add a preference, with other preferences in xml file:
Other solutions didn’t work for me because I ALSO had an xml with preferences. I’m not sure all these calls are necessary/redundant, but this works.

onCreate() method, class extends PreferenceActivity:

setContentView(R.layout.preferences);
addPreferencesFromResource(R.xml.preferences);

PreferenceScreen pScreen = getPreferenceManager().createPreferenceScreen(this);     
CheckBoxPreference cb = new CheckBoxPreference(this);
cb.setKey("cb");
cb.setTitle("BLAH");
cb.setOrder(99);        //not working...
pScreen.addPreference(cb);

setPreferenceScreen(pScreen);
addPreferencesFromResource(R.xml.preferences);

Sidenote: Since I needed to generate a dynamic checkbox list, it was best suited inside an inner PreferenceScreen. So I created this PreferenceScreen inside the xml, then dynamically generated the checkboxes inside this. This way the ordering didn’t matter since all the ‘new’ dynamica checkboxes were inside this screen.

Leave a Reply

Your email address will not be published. Required fields are marked *