public class SettingsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
getFragmentManager().beginTransaction()
.add(R.id.settingsContainer, new SettingsFragment())
.commit();
}
public static class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
#Override
public void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals("aKey") {
Preference pref = findPreference(key);
pref.setSummary(sharedPreferences.getString(key, ""));
}
}
}
}
When the user changes his preferences they are stored and showed by the listener.
When the activity is restarted I lost all the summaries, but values are correctly stored because they are retrieved if I click on each preference.
I'd like to show what was done before, not default values.
In your onResume() method after registering the listener just call the listener with every preference key.
#Override
public void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
onSharedPreferenceChanged(getPreferenceScreen().getSharedPreferences(), "your_key");
}
when the Fragment was created, you call the following method:
addPreferencesFromResource(R.xml.preferences)
the if the xml file preferences content is stationary, and you change another preference file when accept onSharedPreferenceChanged.
May you can get values with method getActivity().getSharedPreferences().
Related
I've my main activity that starts a new activity (SearchResultsActivity).
I also have a settings menu.
I want my SearchResultsActivity to be notified every time there is a new/edited setting from the settings menu.
I'm implementing the OnSharedPreferenceChangeListener the interface on SearchResultsActivity and registering itself to listen to any modification in the settings but for some odd reason the callback is never executed.
Here's my SearchResultsActivity code
public class SearchResultsActivity extends BaseActivity implements SearchResultsFragment.RouteResultsFragmentCommunicator, SharedPreferences.OnSharedPreferenceChangeListener {
private static final String TAG = SearchResultsActivity.class.getSimpleName();
private FragmentManager mFragmentManager;
private SearchResultsFragment mSearchResultsFragment;
private RouteFragment mRouteFragment;
private SharedPreferences pref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_results);
// Set the toolbar
activateToolbarWithHomeEnabled();
pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
// Initialize the FragmentManager
mFragmentManager = getFragmentManager();
mSearchResultsFragment = (SearchResultsFragment) mFragmentManager.findFragmentById(R.id.searchRouteResultsFragment);
}
#Override
protected void onResume() {
super.onResume();
pref.registerOnSharedPreferenceChangeListener(this);
}
#Override
protected void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
#Override
protected void onStop() {
EventBus.getDefault().unregister(this);
super.onStop();
}
#Override
protected void onPause() {
pref.unregisterOnSharedPreferenceChangeListener(this);
super.onPause();
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Log.d(TAG, "onSharedPreferenceChanged callback");
}
}
For sake of simplicity I've removed parts of the code that has nothing to do with my issue.
So my problem is, "onSharedPreferenceChanged callback" is never printed on the logcat when I make a change on any setting.
Just in case, here's my settings implementation:
public class MySettings extends BaseActivity {
private static final String TAG = MySettings.class.getSimpleName();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pref_with_actionbar);
// Set the toolbar
activateToolbarWithHomeEnabled();
getFragmentManager().beginTransaction().replace(R.id.content_frame, new MyPreferenceFragment()).commit();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id==android.R.id.home) {
finish();
return true;
}
else {
return super.onOptionsItemSelected(item);
}
}
}
And the fragment:
public class MyPreferenceFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
private static final String TAG = MyPreferenceFragment.class.getSimpleName();
private EditTextPreference mMaxRadius;
private SharedPreferences mSharedPreferences;
private CheckBoxPreference mCheckBoxPreference;
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
mMaxRadius = (EditTextPreference) findPreference(getResources().getString(R.string.pref_radius_key));
mSharedPreferences = getPreferenceManager().getSharedPreferences();
String maxRadius = mSharedPreferences.getString(getResources().getString(R.string.pref_radius_key), "Unknown");
mMaxRadius.setSummary("Max Radius: " + maxRadius);
mCheckBoxPreference = (CheckBoxPreference) findPreference(getString(R.string.pref_order_list_key));
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equalsIgnoreCase(getResources().getString(R.string.pref_radius_key))) {
Preference connectionPref = findPreference(key);
// Set summary to be the user-description for the selected value
connectionPref.setSummary(sharedPreferences.getString(key, "Unknown") + " km");
}
else if (key.equalsIgnoreCase(getString(R.string.pref_order_list_key))) {
Preference orderByPreference = findPreference(key);
}
}
#Override
public void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
}
Please note that on MyPreferenceFragment the onSharedPreferenceChanged is called as expected, eveytime there is a settings change the MyPreferenceFragment#onSharedPreferenceChanged is executed. But SearchResultsActivity#onSharedPreferenceChanged is never called.
Can someone explain me what is wrong with SearchResultsActivity#onSharedPreferenceChanged never being executed when I change something on the settings?
Register your listener in onCreate() and unregister in onDestroy(). When you start the preference activity your main activity is paused, and unregisters.
I've got a problem with updating the summary value of a PreferncesFragment. I have tried to follow the advice of the post : Updating sharedPreferences Summary via listener but it doesn't work ! The summary doesn't update...
I don't understand what is wrong ? Thank's for your help !
My pref file :
<CheckBoxPreference
android:key="is_title"
android:summary="#string/conf_istitle_sum"
android:title="#string/conf_istitle_title"
android:defaultValue="true"
/>
<EditTextPreference
android:key="sms_title"
android:title="#string/conf_sms_title"
android:summary="#string/msgtitre"
android:dialogTitle="#string/conf_diagsms_title"
android:dialogMessage="#string/conf_diagsms_sum"
android:defaultValue="#string/msgtitre"
/>
My Preference class :
public class SetPreferenceActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener
{
protected MyPreferenceFragment settingsFragment;
#Override
protected void onCreate(final Bundle savedInstanceState)
{ settingsFragment = new MyPreferenceFragment();
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction().replace(android.R.id.content,
settingsFragment).commit();
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
if (key.equals("sms_title")) {
String newValue = sharedPreferences.getString(key, "");
settingsFragment.findPreference(key).setSummary(newValue);
}
}
public static class MyPreferenceFragment extends PreferenceFragment
{
#Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
}
What's working is the "old" solution deprecated OldPreferences
Please check whether onSharedPreferenceChanged is being called at all. You need to register the handler with your preferences. First,
get a reference to your preferences in onCreate:
public class SettingsActivity
extends AppCompatActivity
implements SharedPreferences.OnSharedPreferenceChangeListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
// ...
}
In the lifecycle of the Activity (note that I am using a plain AppCompatActivityrather than a PreferenceActiviy) register the handeler.
#Override
protected void onPause() {
super.onPause();
preferences.unregisterOnSharedPreferenceChangeListener(this);
}
#Override
protected void onResume() {
super.onResume();
preferences.registerOnSharedPreferenceChangeListener(this);
}
Now, the handler should be called:
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Log.d(DEBUG_TAG, key);
// fragment.findPreference(key) //... TBD
}
I have followed the Google dev docs and come up with the following shared preference activity:
public class SettingsActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener {
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Display the fragment as the main content.
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new SettingsFragment())
.commit();
}
public static class SettingsFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
}
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
// TODO Auto-generated method stub
Toast.makeText(this, "Pref changed", Toast.LENGTH_SHORT).show();
}
#Override
protected void onResume() {
super.onResume();
getApplicationContext().getSharedPreferences(this.getLocalClassName(), MODE_PRIVATE).registerOnSharedPreferenceChangeListener(this);
//Toast.makeText(this, "registered pref listener", Toast.LENGTH_SHORT).show();
}
#Override
protected void onPause() {
super.onPause();
getApplicationContext().getSharedPreferences(this.getLocalClassName(), MODE_PRIVATE).unregisterOnSharedPreferenceChangeListener(this);
}
}
As you can see, I have a simple toast message in the onSharedPreferenceChanged method so I can see it working, but it doesn't seem to work.
The only difference with the Google docs is that I am using getApplicationContext() instead of getPreferenceScreen() in the onResume(), because getPreferenceScreen() is showing up as deprecated.
I just need to figure out why its not listening - my preference screen is just full of checkboxes, so I would assume, when I click any of them, the onSharedPreferenceChanged() method is called and I would see my toast.
This simple one has got me stumped.
You are registering your listener to a wrong preference.
Loaded preference from XML resource in SettingsFragment uses default shared preferences so you should register the listener like this:
#Override
public void onResume() {
super.onResume();
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
pref.registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onPause() {
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
pref.unregisterOnSharedPreferenceChangeListener(this);
super.onPause();
}
I have preference xml and following code:
public class MainActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener
{
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Toast.makeText(getApplicationContext(), "DO SOMETHING", Toast.LENGTH_LONG).show();
}
}
I want to get notified over toast message, when one or more preferences are changed. I think upper code should work, but for some reason it doesn't.
I have for example CheckBoxPreference in my xml file. And when I check or uncheck CheckBox I want to be notified.
You have to set the listener like this for example:
PreferenceManager.getDefaultSharedPreferences(this).
registerOnSharedPreferenceChangeListener(this);
or, if You donĀ“t use the default shared preferences, You have to get Your prefs and then register them:
SharedPreferences preferences = getSharedPreferences("your_shared_prefs", Context.MODE_PRIVATE);
preferences.registerOnSharedPreferenceChangeListener(this);
You should register to listen to the shared preference changes:
#Override
public void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
#Override
public void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
I am trying to create an App where the preference summary changes based on the checked state of a CheckBoxPreference.
I am not quite sure how to query preferences since a good old isChecked() won't work.
Would be much simpler if you just used android:summaryOff and android:summaryOn in your preference layout. No code required. E.g:
<CheckBoxPreference
android:enabled="true"
android:key="alerts"
android:title="Alerts"
android:summaryOn="You will get notified when something interesting happens"
android:summaryOff="You will not be notified"
/>
See: http://developer.android.com/reference/android/preference/CheckBoxPreference.html
public class Preferences extends PreferenceActivity
implements OnSharedPreferenceChangeListener {
public final static String KEY_CHECK = "check";
private CheckBoxPreference mCheckBoxPreference;
#Override
public void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
addPreferencesFromResource(R.xml.preferences);
mCheckBoxPreference = (CheckBoxPreference) getPreferenceScreen()
.findPreference(KEY_CHECK);
}
#Override
protected void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}
#Override
protected void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
if (key.equals(KEY_CHECK)) {
if (mCheckPreference.isChecked()) {
mCheckPreference.setSummary(mCheckPreference.getEntry());
}
}
}
}