Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use sharedPreferences outside of an Activity?

Tags:

android

mvvm

I've been stuck on this very simple problem for hours now and Ive been unable to find any suitable solutions through google.

I am trying to use the SharedPreferences class in the model layer of my application. Specifically I want to be able to save or fetch the user name and the corresponding token whenever the application is started(if the user sets the application up for auto login that is).

Is there a way for me to use SharedPreferences for this issue or am I forced into using FileInput/Output ?

like image 366
CodePrimate Avatar asked Feb 08 '12 11:02

CodePrimate


2 Answers

Where do you instantiate your Model class?

Just pass either a context or the SharedPreferences to the constructor:

public class Model {
    private final Context context;
    private final SharedPreferences sharedPrefs;

    public Model(Context context) {
        this.context = context;
        sharedPrefs = context.getSharedPreferences("name", 0);
    }

    private String doSomething(){
        return sharedPrefs.getString("key", "defValue");
    }
}
like image 89
Blundell Avatar answered Oct 19 '22 12:10

Blundell


SharedPreferences isn't called only from Activity, but from Context (which Activity extends) so you can use the application context as well.

like image 24
MByD Avatar answered Oct 19 '22 14:10

MByD