简体   繁体   中英

When I change value in Shared Preference app got crash

http://i.stack.imgur.com/vnfQt.png

As shown above From settings when I change the value of temprature units from metric to imperial and press back button my app got crash and showing below error

http://i.stack.imgur.com/dBeHk.png

SettingsActivity

    package com.example.poo.sunshine;

    import android.app.Activity;
    import android.content.SharedPreferences;
    import android.os.Bundle;
    import android.preference.ListPreference;
    import android.preference.Preference;
    import android.preference.PreferenceFragment;
    import android.preference.PreferenceManager;

    public class SettingsActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Display the fragment as the main content.
        getFragmentManager().beginTransaction()
                .replace(R.id.container, new MyPreferenceFragment())
                .commit();
    }

    public static class MyPreferenceFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            // Add 'general' preferences, defined in the XML file
            addPreferencesFromResource(R.xml.pref_general);

            // For all preferences, attach an OnPreferenceChangeListener so the UI summary can be
            // updated when the preference changes.
            PreferenceManager.getDefaultSharedPreferences(getActivity()).registerOnSharedPreferenceChangeListener(this);

        }

        @Override
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
            Preference locationPref = findPreference(getString(R.string.pref_location_key));
            Preference unitsPref = findPreference(getString(R.string.pref_units_key));
            prefChanged(sharedPreferences, locationPref, key);
            prefChanged(sharedPreferences, unitsPref, key);
        }

        private void prefChanged(SharedPreferences sharedPreferences, Preference pref, String key) {
            if (sharedPreferences instanceof ListPreference) {
                // For list preferences, look up the correct display value in
                // the preference's 'entries' list (since they have separate labels/values).
                ListPreference listPreference = (ListPreference) sharedPreferences;
                int prefIndex = listPreference.findIndexOfValue(key);
                if (prefIndex >= 0) {
                    pref.setSummary(listPreference.getEntries()[prefIndex]);
                } else {
                    pref.setSummary(sharedPreferences.getString(key, ""));
                }    
            }    
        }
    }
}

The problem is cause from the view of your Fragment is not yet attached to your SettingActivity.

To avoid this error, you can check with isAdded() before access views in your Fragment.

@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        if(isAdded()){
            Preference locationPref = findPreference(getString(R.string.pref_location_key));
            Preference unitsPref = findPreference(getString(R.string.pref_units_key));
            prefChanged(sharedPreferences, locationPref, key);
            prefChanged(sharedPreferences, unitsPref, key);
        }

}

Another solution and I would like to suggest as well. You should register the preference changed listener in onViewCreated() in your Fragment. So that mean your Fragment is fully attached.

 @Override
 public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        PreferenceManager.getDefaultSharedPreferences(getActivity())
        .registerOnSharedPreferenceChangeListener(this);
 }

Hope this will work!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM