StinsonMaster StinsonMaster - 12 days ago 5
Android Question

Load/Save settings from/to database in PreferenceFragment

Users can add projects in my app and I have a PreferenceFragment for settings of the projects.

This is my Fragment:

public class SettingsFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

addPreferencesFromResource(R.xml.project_settings);
}
}


And my Activity:

public class Settings extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

getFragmentManager().beginTransaction()
.replace(android.R.id.content, new SettingsFragment())
.commit();
}
}


The availabal settings for each project are identical but the data should be saved per project (e.g. the project name). So how can I save the preferences to my sqlite database?

Answer

The answer is a Preference.OnPreferenceChangeListener and some magic inside the onPreferenceChange method.