I have an Activity
which when clicking the menu and a button appearing there, goes to a PreferenceActivity
, and then loads three ListPreferences
.
The ListPreference
lets the user choose several values to update a remote DB, and I would like that to save those values when the application goes paused for example.
As the ListPreference
are in the PreferenceActivity
, how can I get those values?
Where should I save the current preferences state, in the Activity
or in the PreferenceActivity
?
This is what I have done so far in my Activity.java
:
[...]
private void updateFromPreferences() {
Context context = getApplicationContext();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
callsFrequencyUpdate = Integer.parseInt(prefs.getString(Preferences.CALLS_FREQUENCY_PREF, "0"));
smsFrequencyUpdate = Integer.parseInt(prefs.getString(Preferences.SMS_FREQUENCY_PREF, "0"));
locationFrequencyUpdate = Integer.parseInt(prefs.getString(Preferences.LOCATION_FREQUENCY_PREF, "0"));
}
private void savePreferences() {
SharedPreferences activityPreferences = getPreferences(Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = activityPreferences.edit();
editor.putInt(Preferences.CALLS_FREQUENCY_PREF, callsFrequencyUpdate);
editor.putInt(Preferences.SMS_FREQUENCY_PREF, smsFrequencyUpdate);
editor.putInt(Preferences.LOCATION_FREQUENCY_PREF, locationFrequencyUpdate);
editor.commit();
}
@Override
protected void onPause() {
super.onPause();
savePreferences();
}
And this is my Preferences.java
file:
public class Preferences extends PreferenceActivity {
public static final String CALLS_FREQUENCY_PREF = "CALLS_FREQUENCY_PREF";
public static final String SMS_FREQUENCY_PREF = "SMS_FREQUENCY_PREF";
public static final String LOCATION_FREQUENCY_PREF = "LOCATION_FREQUENCY_PREF";
SharedPreferences prefs;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
Thanks a lot in advance!