简体   繁体   中英

Access shared preference from many classes

I need to be able to access a share preference object from through out my app from many different classes that extend a range of types.

Currently I have been doing this by creating a static variable within the start activity of the app.

...
        public static SharedPreferences sharedpreferences;
        SharedPreferences.Editor editor;

        public void onCreate(Bundle savedInstanceState) {
            sharedpreferences = getSharedPreferences("PrefFile", MODE_PRIVATE); 
            editor = sharedpreferences.edit();
                ...
        }
...

And then from within the other class I access it via: StartActivity.sharedpreferences

For the most part this works fine, however if the app is left and still running in the background and the user comes back to the app so that it goes back to the last activity and does not re run the start activity, StartActivity.sharedpreferences is now null and so a NullPointerExecption gets raised if I try to access it.

How would I go about allowing multiple classes access the same shared preference variable without it ever becoming Null

Create a singleton instance of it that will be initialized on first get method.

private static class SingletonHolder {
    private static SharedPreferences INSTANCE = getSharedPreferences("PrefFile", MODE_PRIVATE); 
}

public static SharedPreferences getSharedPreferences() {
    return SingletonHolder.INSTANCE;
} 

Create singleton class like this:

    public class AppPreferences {
        private SharedPreferences sPreferences;
        public static void init(Context context) {
            sPreferences = context.getSharedPreferences(PREFERENCES_NAME, 0);
        }

        public static SharedPreferences getPrefs() {
            return sPreferences;
        }
    }

Then create a custom Application subclass:

    public class App extends Application {

        @Override
        public void onCreate() {
            super.onCreate();
            AppPreferences.init(this);
        }
    }

And add it in your AndroidManifest.xml:

    <application
        android:name="com.example.App"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
    ...

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