Barak
Barak

Reputation: 16393

SharedPreferences and Application class

I have many shared preference for my app (mostly relating to color customization) and I'm unsure what the best method is to store/use them at runtime.

Currently I am doing something like this (with more or less preferences depending on the view) in every activity/fragment:

SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getActivity());
int buttonbg = settings.getInt("buttonmenu_bg", 0);
int buttontxt = settings.getInt("buttonmenu_txt", 0);
int headerclr = settings.getInt("header", 0);

And then using those to set the various colors in the display. This seems like a lot of overhead to have to call the PreferenceManager each time and go through all that.

So I started looking at creating an application class, reading the preferences in once and using static variables from the application class in the activities/fragment to set the display.

My question is, are there any drawbacks or gotchas to doing this that I should consider before I venture further down the Application class path?

Upvotes: 0

Views: 3582

Answers (3)

Andrés Pachon
Andrés Pachon

Reputation: 838

The purpose of the Application class is to store global application state or data (in memory of course), so your approach is correct. I've used it multiple times and it works like a charm.

What I usually do is to create a Map member variable and provide methods for getting and putting values into it, looks like this:

package com.test;
...
...
public class MyApp extends Application{

    private Map<String, Object> mData;

    @Override
    public void onCreate() {
        super.onCreate();
        mData = new HashMap<String, Object>();
    }

    public Object get(String key){
        return mData.get(key);
    }
    public void put(String key,Object value){
        mData.put(key, value);
    }
}

Then from my activities, I just do ((MyApp) getApplication()).get("key") or ((MyApp) getApplication()).put("key",object). Also, don't forget to set the android:name attribute in your manifest file, under the application tag:

<application
        ...
        ...
        android:name="com.test.MyApp"> 
</application>

Upvotes: 0

Sparky
Sparky

Reputation: 8477

Is there any particular reason why you are not setting the display colors in res/values/styles.xml?

Upvotes: 0

Arun Badole
Arun Badole

Reputation: 11097

If you are not using so many static variables so this may not affect your application.But the problem with static variable may arise when your app goes to background and the app running on front requires memory so it may clear your static data,so when you will go to your app you may find nothing (null) in place of static data.

Upvotes: 2

Related Questions