Listening for SharedPreferences changes in MainActivity
<p>I am trying to listen <code>SharedPreferences</code> changes in the <code>MainActivity</code>. And update the values in the settings of the app. And the working code goes like:</p>

<pre><code>private SharedPreferences SP, prefs;
SharedPreferences.OnSharedPreferenceChangeListener mListener;
SP = PreferenceManager.getDefaultSharedPreferences(getBaseContext());

mListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
    public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {

        Toast.makeText(MainActivity.this, "Key changed: "+key, Toast.LENGTH_SHORT).show();
    }
};

SP.registerOnSharedPreferenceChangeListener(mListener);
</code></pre>

<p>But when I try to change the key value like this. It says can not resolve <code>findPreference</code> method. I tried doing it using context but still the error persists.</p>

<pre><code>private SharedPreferences SP, prefs;
SharedPreferences.OnSharedPreferenceChangeListener mListener;
SP = PreferenceManager.getDefaultSharedPreferences(getBaseContext());

mListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
    public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {

            if (key.equals("username")) {
                Preference pref = findPreference(key);
                pref.setDefaultValue(prefs.getString(key, "bob"));    }
};
SP.registerOnSharedPreferenceChangeListener(mListener);
</code></pre>

<p>How can we import the method definition in <code>MainActivity</code>. Please tell if the way I am changing value here, if correct? </p>

<p>Settings.java</p>

<pre><code>import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.os.Bundle;

public class Settings extends PreferenceActivity {



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getFragmentManager().beginTransaction().replace(android.R.id.content, new MyPreferenceFragment()).commit();
    }

    public static class MyPreferenceFragment extends PreferenceFragment
    {
        PrefManager prefManager;
        @Override
        public void onCreate(final Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.preferences);
        }
    }

}
</code></pre>

<p>preferences.xml</p>

<pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"&gt;
    &lt;EditTextPreference android:title="Your Name"
        android:key="username"
        android:summary="Please provide your username"&gt;
    &lt;/EditTextPreference&gt;


&lt;/PreferenceScreen&gt;
</code></pre>

<p>I basically want to update the Preference in the settings page whenever <code>SharedPreferences</code> of key "<code>username</code>" is getting changed in the code.</p>