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.

13 comments:

  1. We can customise each report - freed from charge - together with purchasing stand-alone sections or country-level reviews, as well as|in addition to} supply inexpensive discounts for start-ups & universities. Ou'll be rewarded together with your free $10 sign-up bonus instantly after registration. From there, you'll must wager 1x to make thecasinosource.com the "free cash" winnings withdrawable.

    ReplyDelete