1

I want to have my application preferences accessible in every activity. I don't want to have to get all of the SharedPreferences in every activity. but instead get SharedPreferences once, and have a global object that has values for all these preferences, like if (AppSettings.isSoundOn()) {// do stuff} and have that object available everywhere with no ifs and buts.

I tried using static classes but you can't get Shared Preferences from a static class. Also it looks like that the class you get SharedPreferences in has to extend Activity, or it produces an error.

I'm sure there is a stupidly simple way this is usually done, as it is basic app functionality, but none of the Android development books I have actually covers how to deal with application wide preferences, and any tutorials I could find just cover setting and getting SharedPreferences which is simple, but you have to do it in every activity.

L84
  • 974
  • 2
  • 11
  • 21
  • 1
    Extend the `Application` class. http://stackoverflow.com/questions/4051875/what-is-the-best-way-to-use-shared-preferences-between-activities?rq=1 – Simon Sep 08 '13 at 11:24

1 Answers1

2

Create a class like MyApplication and extends from android.app.Application. In there you can access the sharedpreferences.

In every Activity you can get the Application by using MyApplication app = (MyApplication)this.getApplication();

In MyApplication put a public method that gets the Sharedpreference and one that stores it.

dumazy
  • 13,857
  • 12
  • 66
  • 113
  • Ok, this works, but what does `MyApplication app = (MyApplication)this.getApplication();` do? (specifically the `(MyApplication)this.getApplication()` part. Also, wouldn't it mean that every time I want to access the settings, the `onCreate()` of the MyApplication class would have to run and do whatever it does (in this case read from SharedPreferences)? Isn't that wasteful just to get a few boolean values? – L84 Sep 08 '13 at 13:06
  • 2
    no, the onCreate() of MyApplication runs only once, when the app is launched for the first time, until it's destroyed (user removes it from recent apps, stops it in the App settings, or the system stops it because it needs memory). getApplication() gives you the Application class of your app, always. You have to cast it to MyApplication to use the methods that you've put in it – dumazy Sep 08 '13 at 17:16