Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: using SharedPreferences in a library

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?

like image 794
BlackNeko Avatar asked Oct 26 '10 17:10

BlackNeko


Video Answer


1 Answers

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: Accessing SharedPreferences through static methods

But IMHO the first solution would be the best.

like image 122
mreichelt Avatar answered Sep 27 '22 20:09

mreichelt