views:

31

answers:

2

I made a library that I use across my app. I want it to access some settings that are stored in the shared preferences.

This is a shortened version of my library:

package com.android.foobar;

import android.content.SharedPreferences;
import android.preference.PreferenceManager;

public class Lib {
    int now;

    public Lib() {
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
        now = settings.getInt("now", 435);
    }

    public int foo(){
        return now;
    }
}

I've been looking for an answer and experimenting, but I can't find a valid context to pass to getDefaultSharedPreferences(). Any ideas?

+1  A: 

The most easiest way would be to include the context as a parameter of your Lib constructor and pass the application context from the point where your Lib is created.

If you search for a static way of how to do it have a look at this: http://stackoverflow.com/questions/3806051/accessing-sharedpreferences-through-static-methods/3806138#3806138

But IMHO the first solution would be the best.

mreichelt
A: 

Similar question answered here, hope it helps!

Josh