Niyoko
Niyoko

Reputation: 7672

Accessing SharedPreferences without context

I have read question : this and this about reading shared preferences. But they still need Context to access SharedPreferences. I want to know how to access SharedPreferences without context. Thanks in advance

Upvotes: 17

Views: 27446

Answers (4)

80sTron
80sTron

Reputation: 121

Oded's answer got me what I needed for my callback method in my utility class. In my case I needed a kotlin version which looks like this.

manifest

android:name=".SGAutoApp"

SGAutoApp.kt

class SGAutoApp : Application() {
    companion object {
        fun getAppContext(): Context {
            return this.getAppContext()
        }
    }
}

and then it's like below in my utility class callback method.

            val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(SGAutoApp.getAppContext())

Upvotes: -1

Code Spy
Code Spy

Reputation: 9964

We can have SharedPreference instance to use in a helper class having Getters and Setters, Without involving context explained here

In MainActivity add

public static SharedPreferences preferences;
preferences = getSharedPreferences( getPackageName() + "_preferences", MODE_PRIVATE);

Then in PreferenceHelper use set and get as

public static void setName(String value) {
    MainActivity.preferences.edit().putString(KEY_DEMO_NAME, value ).commit();
}
public static String getName() {
    return MainActivity.preferences.getString(KEY_DEMO_NAME,"");
}

Upvotes: 6

Oded Breiner
Oded Breiner

Reputation: 29749

Application Class:

import android.app.Application;
import android.content.Context;

public class MyApplication extends Application {

    private static Context mContext;

    public void onCreate() {
        super.onCreate();
        mContext = getApplicationContext();
    }

    public static Context getAppContext() {
        return mContext;
    }

}

Declare the Application in the AndroidManifest:

<application android:name=".MyApplication"
    ...
/>

Usage:

PreferenceManager.getDefaultSharedPreferences(MyApplication.getAppContext());

Upvotes: 8

Niyoko
Niyoko

Reputation: 7672

I solve my problem by retrieve ApplicationContext first (this) and then use that context to get SharedPreferences. thank K-ballo.

Upvotes: 15

Related Questions