L84
L84

Reputation: 984

Using Shared Preferences in every activity

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.

Upvotes: 1

Views: 853

Answers (1)

dumazy
dumazy

Reputation: 14435

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.

Upvotes: 2

Related Questions