Monday, June 20, 2011

Using SharedPreferences in Android Properly

The use of SharedPreferences outside of an Activity Class can become very tedious. This is because PreferenceManager.getDefaultSharedPreferences(Context context) requires a context object. In order to simplify things an easy solution is to use the Application object like this.


public class MyApplication extends Application {

   public static SharedPreferences settings;

   @Override
   public void onCreate() {
      super.onCreate();
      settings=PreferenceManager.
            getDefaultSharedPreferences(this);
   }
}

This code will work because the Application object is created before all other activities, hence the initialization is guaranteed. Now the SharedPreferences can be simply statically accessed via MyApplication.settings.

No comments:

Post a Comment