Can't resolve findPreference() from MainActivity?

4.4k views Asked by At

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, ""));
                    }
                }
            }
        }
    }
1

There are 1 answers

1
Lyla On BEST ANSWER

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.