I'm getting a compiler error cannot resolve method findPreference when I try to intialize an OnSharedPreferencesChanged listener in my MainActivity. According to the answer here:
findPreference() should be called from a class implementing PreferenceActivity interface
but I don't understand what the code to do this would be. How can I get rid of the compiler error and successfully set listeners for preference changes?
MainActivity.java
public class MainActivity extends FragmentActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
private SharedPreferences.OnSharedPreferenceChangeListener listener;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
//Test preference menu
listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
if (key.equals("pref_wood")) {
Preference woodPref = findPreference(key); //COMPILER ERROR HERE
MainActivity.getGLSurfaceView().setTexture("");
// Set summary to be the user-description for the selected value
woodPref.setSummary(sharedPreferences.getString(key, ""));
}
}
}
}
}
findPreference is a method which is part of both PreferenceFragment and PreferenceActivity - these are the Fragments/Activities that actually show your Preference screen (the activity is deprecated and you should be using the PreferenceFragment).
You're trying to use it in your MainActivity. This doesn't work because the Preference objects don't actually exist on this screen (they exist in another activity that usually have a PreferenceFragment as part of it). If you need to get access to a preference value of a preference in an activity that is not your preference screen, use SharedPreferences, something like:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getBoolean(R.bool.saved_high_score_default);
boolean wood = sharedPref.getBoolean(pref_wood, defaultValue);
You can check out the documentation for further examples.
If your MainActivity is supposed to be a screen that shows settings, then you should probably rename it and include a preference fragment inside of it.
I believe you're also going to run into trouble with setSummary because the Preference is not part of this activity, it's part of the activity where you actually modify the preferences. setSummary is used to update the actual UI of the Preference so that if you, for example, select one of three values when using a list preference, it shows the value you just selected on the screen.
I am implementing the Settings for my android app through the PreferenceFragment.
My android:summary for the different Preferences should display the current value at all times therefore I have read through severals posts and the official documentation.
Although I got it working technically my solution seems kind of hacky and I am now searching for best practice since I found no good source on how it is meant to be properly implemented.
For example I implemented onSharedPreferenceChanged to listen for changes and to update the UI, but after every restart of the PreferenceFragment, the initial android:summary is shown again. To solve this I added this to the onCreate
// display current value in the UI
EditTextPreference editText = (EditTextPreference) findPreference("serverAddress");
editText.setSummary(editText.getText());
Is this is how it is supposed to be done or am I misunderstanding something ?
Full Code:
public class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
public static final String KEY_PREF_SERVER_ADDRESS = "serverAddress";
public static final String KEY_PREF_GENDER = "gender";
public SettingsFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle saveInstanceState) {
super.onCreate(saveInstanceState);
//Load the preferences from the XML file
addPreferencesFromResource(R.xml.preferences);
// display current value in the UI
EditTextPreference editText = (EditTextPreference) findPreference("serverAddress");
editText.setSummary(editText.getText());
}
// Listen for settings changes and update the UI
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals(KEY_PREF_SERVER_ADDRESS)) {
Preference serverAddressPref = findPreference(key);
//Set UI to display updated summary
serverAddressPref.setSummary(sharedPreferences.getString(key, ""));
}
if (key.equals(KEY_PREF_GENDER)) {
Preference serverAddressPref = findPreference(key);
//Set UI to display updated summary
serverAddressPref.setSummary(sharedPreferences.getString(key, ""));
}
}
#Override
public void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}
}
In Android 4, I have a preference value that I want to appear in the standard form E2C56DB5-DFFB-48D2-B060-D0F5A71096E0. But the user may enter the value without dashes. I would like to allow the user to enter it with any combination of whitespace or dashes, and simply have my code normalize it.
I am using the code below, and I see the log line, but it does nothing. I am guessing this is because Android has another Editor object open that overwrites my changes. Is there any other way to accomplish this?
public class UuidFragment extends PreferenceFragment {
...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
this.getPreferenceScreen().findPreference("pref_uuid").setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference,
Object newValue) {
if (newValue.toString().length() != 0) {
String normalizedUuid=normalizeUuid(newValue.toString());
// TODO: this code runs but does nothing, I think because after committing the change, there is a higher level editor that commits the old value
// thereby undoing this change
if (!normalizedUuid.equals(newValue.toString())) {
Log.d(TAG, "Adjusting uuid from "+newValue.toString()+" to "+normalizedUuid);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(UuidFragment.this.getActivity());
SharedPreferences.Editor editor = settings.edit();
editor.putString(preference.getKey(), normalizedUuid);
editor.commit();
}
return true;
}
}
});
}
}
Try subclassing EditTextPreference and overriding setText(). In your setText() method, fix up the passed-in string before chaining to the superclass. Then, reference your EditTextPreference subclass from your preference XML.
in the onCreate method of my PreferenceActivity i set some Properties like this:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("pref_mykey", true);
editor.commit();
It seems to work but the View is not updating so when i open the properties the onCreate runs and changes the values. I will then see the "old" values on the Screen until i close and reopen the prefs screen, then i do see the new properties.
I already tried this after the commit:
((BaseAdapter) getPreferenceScreen().getRootAdapter()).notifyDataSetChanged();
But without any effect. I still see the "old" Prefs until i close and reopen the PreferenceActivity .
What am i doing wrong? How can i refresh the PreferenceActivity after setting values in the onCreate method?
Thanks a lot for your help.
This was buggin me all day but finally found a solution.
((ListPreference)getPreferenceScreen().findPreference("key_of_preference_in_xml_file")).setValue(code);
Your example is with a boolean so it'll have to change based on what kind of preference it is.
IE:
((CheckBoxPreference)getPreferenceScreen().findPreference("key_of_preference_in_xml_file")).setChecked(true);
If you use a PreferenceFragment than you need to inject the PreferenceScreen in the activity.
public class SettingsActivity extends Activity implements ScanFragment.OnFragmentInteractionListener {
private PreferenceScreen prefScreen;
public void setPreferenceScreen(PreferenceScreen prefScreen){
this.prefScreen = prefScreen;
}
#Override
public void onFragmentInteraction(String scanContent) {
// commiting to editor retrieved from preference manager would not refresh view
EditTextPreference pref = (EditTextPreference)this.prefScreen.findPreference(getString(R.string.preference_url_key));
pref.setText(scanContent);
}
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);
((SettingsActivity)this.getActivity()).setPreferenceScreen(this.getPreferenceScreen());
}
}
}
I'm registering a preference change listener like this (in the onCreate() of my main activity):
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.registerOnSharedPreferenceChangeListener(
new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(
SharedPreferences prefs, String key) {
System.out.println(key);
}
});
The trouble is, the listener is not always called. It works for the first few times a preference is changed, and then it is no longer called until I uninstall and reinstall the app. No amount of restarting the application seems to fix it.
I found a mailing list thread reporting the same problem, but no one really answered him. What am I doing wrong?
This is a sneaky one. SharedPreferences keeps listeners in a WeakHashMap. This means that you cannot use an anonymous inner class as a listener, as it will become the target of garbage collection as soon as you leave the current scope. It will work at first, but eventually, will get garbage collected, removed from the WeakHashMap and stop working.
Keep a reference to the listener in a field of your class and you will be OK, provided your class instance is not destroyed.
i.e. instead of:
prefs.registerOnSharedPreferenceChangeListener(
new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
// Implementation
}
});
do this:
// Use instance field for listener
// It will not be gc'd as long as this instance is kept referenced
listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
// Implementation
}
};
prefs.registerOnSharedPreferenceChangeListener(listener);
The reason unregistering in the onDestroy method fixes the problem is because to do that you had to save the listener in a field, therefore preventing the issue. It's the saving the listener in a field that fixes the problem, not the unregistering in onDestroy.
UPDATE: The Android docs have been updated with warnings about this behavior. So, oddball behavior remains. But now it's documented.
this accepted answer is ok, as for me it is creating new instance each time the activity resumes
so how about keeping the reference to the listener within the activity
OnSharedPreferenceChangeListener listener = new OnSharedPreferenceChangeListener(){
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
// your stuff
}
};
and in your onResume and onPause
#Override
public void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(listener);
}
#Override
public void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(listener);
}
this will very similar to what you are doing except we are maintaining a hard reference.
The accepted answer creates a SharedPreferenceChangeListener every time onResume is called. #Samuel solves it by making SharedPreferenceListener a member of the Activity class. But there's a third and a more straightforward solution that Google also uses in this codelab. Make your activity class implement the OnSharedPreferenceChangeListener interface and override onSharedPreferenceChanged in the Activity, effectively making the Activity itself a SharedPreferenceListener.
public class MainActivity extends Activity implements SharedPreferences.OnSharedPreferenceChangeListener {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) {
}
#Override
protected void onStart() {
super.onStart();
PreferenceManager.getDefaultSharedPreferences(this)
.registerOnSharedPreferenceChangeListener(this);
}
#Override
protected void onStop() {
super.onStop();
PreferenceManager.getDefaultSharedPreferences(this)
.unregisterOnSharedPreferenceChangeListener(this);
}
}
As this is the most detailed page for the topic I want to add my 50ct.
I had the problem that OnSharedPreferenceChangeListener wasn't called. My SharedPreferences are retrieved at the start of the main Activity by:
prefs = PreferenceManager.getDefaultSharedPreferences(this);
My PreferenceActivity code is short and does nothing except showing the preferences:
public class Preferences extends PreferenceActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// load the XML preferences file
addPreferencesFromResource(R.xml.preferences);
}
}
Every time the menu button is pressed I create the PreferenceActivity from the main Activity:
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
//start Preference activity to show preferences on screen
startActivity(new Intent(this, Preferences.class));
//hook into sharedPreferences. THIS NEEDS TO BE DONE AFTER CREATING THE ACTIVITY!!!
prefs.registerOnSharedPreferenceChangeListener(this);
return false;
}
Note that registering the OnSharedPreferenceChangeListener needs to be done AFTER creating the PreferenceActivity in this case, else the Handler in the main Activity won't be called!!! It took me some sweet time to realize that...
Kotlin Code for register SharedPreferenceChangeListener it detect when change will happening on the saved key :
PreferenceManager.getDefaultSharedPreferences(this)
.registerOnSharedPreferenceChangeListener { sharedPreferences, key ->
if(key=="language") {
//Do Something
}
}
you can put this code in onStart() , or somewhere else..
*Consider that you must use
if(key=="YourKey")
or your codes inside "//Do Something " block will be run wrongly for every change that will happening in any other key in sharedPreferences
So, I don't know if this would really help anyone though, it solved my issue.
Even though I had implemented the OnSharedPreferenceChangeListener as stated by the accepted answer. Still, I had an inconsistency with the listener being called.
I came here to understand that the Android just sends it for garbage collection after some time. So, I looked over at my code.
To my shame, I had not declared the listener GLOBALLY but instead inside the onCreateView. And that was because I listened to the Android Studio telling me to convert the listener to a local variable.
It make sense that the listeners are kept in WeakHashMap.Because most of the time, developers prefer to writing the code like this.
PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).registerOnSharedPreferenceChangeListener(
new OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(
SharedPreferences sharedPreferences, String key) {
Log.i(LOGTAG, "testOnSharedPreferenceChangedWrong key =" + key);
}
});
This may seem not bad. But if the OnSharedPreferenceChangeListeners' container was not WeakHashMap, it would be very bad.If the above code was written in an Activity . Since you are using non-static (anonymous) inner class which will implicitly holds the reference of the enclosing instance. This will cause memory leak.
What's more, If you keep the listener as a field, you could use registerOnSharedPreferenceChangeListener at the start and call unregisterOnSharedPreferenceChangeListener in the end. But you can not access a local variable in a method out of it's scope. So you just have the opportunity to register but no chance to unregister the listener. Thus using WeakHashMap will resolve the problem. This is the way I recommend.
If you make the listener instance as a static field, It will avoid the memory leak caused by non-static inner class. But as the listeners could be multiple, It should be instance-related. This will reduce the cost of handling the onSharedPreferenceChanged callback.
While reading Word readable data shared by first app,we should
Replace
getSharedPreferences("PREF_NAME", Context.MODE_PRIVATE);
with
getSharedPreferences("PREF_NAME", Context.MODE_MULTI_PROCESS);
in second app to get updated value in second app.
But still it is not working...