Bridging Android’s ListPreference and Database
March 1st, 2009 by craigetLong time, no post.. I’ve been waay too busy programming Android for the last few weeks to get anything useful done. As mentioned a few days ago, I’m getting deluged by weird comment spam, so comments are turned off for the moment – sorry.
Today I was trying to mix Android’s two storage mechanisms. The application needs to store a small number of settings which a user can create/update/delete - a database. Additionally, one of these settings is considered to be “selected” – probably SharedPreferences, though one could argue for the database here too. My first intuition was to specialize a subclass of ListPreference to override the getEntries() and getEntryValues() methods – nope. The next idea was to call setEntries(CharSequence[]) and setEntryValues(CharSequence[]) in the constuctor – that seems to work fine. However, since I was reading from a database, I wanted the Cursor to be managed by an activity. Since I was subclassing ListPreference, that wasn’t gonna work. Ultimately, I settled on subclassing PreferenceActivity and building the menus in code instead of XML. Adapting the sample database code from Notepadv3, here is a custom Preferences menu:
public class EditPreferences extends PreferenceActivity { public static final String SELECTED_TARGET_KEY = "SelectedTargetKey"; public static final String NO_SELECTION = "0"; private TargetDbAdapter mDbHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setPreferenceScreen(createPreferenceHierarchy()); } private PreferenceScreen createPreferenceHierarchy() { PreferenceScreen root = getPreferenceManager().createPreferenceScreen(this); PreferenceCategory dialogBasedPrefCat = new PreferenceCategory(this); dialogBasedPrefCat.setTitle(R.string.pref_cat_title); root.addPreference(dialogBasedPrefCat); //builds list from DB mDbHelper = new TargetDbAdapter(this); mDbHelper.open(); Cursor c = mDbHelper.fetchAllNotes(); startManagingCursor(c); int count = c.getCount(); CharSequence[] entries = new CharSequence[count]; CharSequence[] entryValues = new CharSequence[count]; c.moveToFirst(); for(int i=0; i<count; i++) { entries[i] = c.getString(c.getColumnIndexOrThrow(TargetDbAdapter.KEY_TITLE)); entryValues[i] = c.getString(c.getColumnIndexOrThrow(TargetDbAdapter.KEY_ROWID)); c.moveToNext(); } ListPreference targets = new ListPreference(this); targets.setEntries(entries); targets.setEntryValues(entryValues); targets.setDefaultValue(NO_SELECTION); targets.setDialogTitle(R.string.pref_dialog_title); targets.setKey(SELECTED_TARGET_KEY); targets.setTitle(R.string.pref_title); targets.setSummary(R.string.pref_summary); dialogBasedPrefCat.addPreference(targets); //add other preference screens return root; } }
