49

How do you use SharedPreferences in a non-Activity class? I tried making a generic Preferences utility class and importing android.content.Context but Eclipse still wouldn't let me use getSharedPreferences().

Jake Wilson
  • 88,616
  • 93
  • 252
  • 370

12 Answers12

52

SharedPreferences are related to context. You can only reference it through a context.

You can simply pass context as a parameter to your class. For example in the constructor.

In your activity do:

MyClass myClass = new MyClass(this);
Sandor
  • 1,839
  • 2
  • 18
  • 22
51

The solution i found to this was:

1-In an MainActivity class (i.e always launched before getting any context in project) create a static variable for the context:

public static Context contextOfApplication;

2-In an important method of this class (Such as onCreate, the constructor, etc) initialize this variable using the getApplicationContext method:

public void onCreate() {
    contextOfApplication = getApplicationContext();
}

3-In the same class Create a "getter" method for this variable (it must also be static):

public static Context getContextOfApplication(){
    return contextOfApplication;
}

4-In the non-activity class get the context by calling the created method statically:

Context applicationContext = MyActivityClass.getContextOfApplication();

5-Use the PreferenceManager Class to get the SharedPreferences variable:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(applicationContext);

Hope it helps.

Ishan Jindal
  • 198
  • 1
  • 2
  • 18
Santi
  • 1,682
  • 1
  • 13
  • 14
  • 6
    That's a useful workaround, I'd suggest to use contextOfApplication as a private field – fredmaggiowski Jun 17 '15 at 09:37
  • You can also use applicationContext.getSharedPreferences(pref_name, MODE_PRIVATE); – B.shruti Oct 26 '17 at 12:21
  • 3
    This is such a hacky solution and an anti-pattern, exposing a public static Context variable in the Activity. But if you decide to go this way worth noting that since the member `public static Context contextOfApplication;` is public and static, you wouldn't need the `getContextOfApplication()` method to access that. In step 4 you can just do `MyActivityClass.contextOfApplication` and it would work. – PrashanD Jun 24 '18 at 17:17
4

In Kotlin, there's a nice & simple wrapper-based solution – just copy & paste the code into a new AppPreferences.kt file and follow the 4 TODO steps outlined in the code:

import android.content.Context
import android.content.Context.MODE_PRIVATE
import android.content.SharedPreferences
import androidx.core.content.edit

object AppPreferences {
    private var sharedPreferences: SharedPreferences? = null

    // TODO step 1: call `AppPreferences.setup(applicationContext)` in your MainActivity's `onCreate` method
    fun setup(context: Context) {
        // TODO step 2: set your app name here
        sharedPreferences = context.getSharedPreferences("<YOUR_APP_NAME>.sharedprefs", MODE_PRIVATE)
    }

    // TODO step 4: replace these example attributes with your stored values
    var heightInCentimeters: Int?
        get() = Key.HEIGHT.getInt()
        set(value) = Key.HEIGHT.setInt(value)

    var birthdayInMilliseconds: Long?
        get() = Key.BIRTHDAY.getLong()
        set(value) = Key.BIRTHDAY.setLong(value)

    private enum class Key {
        HEIGHT, BIRTHDAY; // TODO step 3: replace these cases with your stored values keys

        fun getBoolean(): Boolean? = if (sharedPreferences!!.contains(name)) sharedPreferences!!.getBoolean(name, false) else null
        fun getFloat(): Float? = if (sharedPreferences!!.contains(name)) sharedPreferences!!.getFloat(name, 0f) else null
        fun getInt(): Int? = if (sharedPreferences!!.contains(name)) sharedPreferences!!.getInt(name, 0) else null
        fun getLong(): Long? = if (sharedPreferences!!.contains(name)) sharedPreferences!!.getLong(name, 0) else null
        fun getString(): String? = if (sharedPreferences!!.contains(name)) sharedPreferences!!.getString(name, "") else null

        fun setBoolean(value: Boolean?) = value?.let { sharedPreferences!!.edit { putBoolean(name, value) } } ?: remove()
        fun setFloat(value: Float?) = value?.let { sharedPreferences!!.edit { putFloat(name, value) } } ?: remove()
        fun setInt(value: Int?) = value?.let { sharedPreferences!!.edit { putInt(name, value) } } ?: remove()
        fun setLong(value: Long?) = value?.let { sharedPreferences!!.edit { putLong(name, value) } } ?: remove()
        fun setString(value: String?) = value?.let { sharedPreferences!!.edit { putString(name, value) } } ?: remove()

        fun remove() = sharedPreferences!!.edit { remove(name) }
    }
}

Now from anywhere within your app you can get a value like this:

val heightInCentimeters: Int? = AppPreferences.heightInCentimeters
val heightOrDefault: Int = AppPreferences.heightInCentimeters ?: 170

Setting a value to the SharedPreferences is just as easy:

AppPreferences.heightInCentimeters = 160 // sets a new value
Jeehut
  • 20,202
  • 8
  • 59
  • 80
2

Using a static method to use SharedPreference without Context Object explained here

In MainActivity before OnCreate

public static SharedPreferences preferences;

In OnCreate method add

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

Create a PreferenceHelper Class with static methods of Getters and Setters

public class PreferenceHelper {

final public static String KEY_DEMO_NAME = "Demo Name";
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,"");
}

}

Code Spy
  • 9,626
  • 4
  • 66
  • 46
2

In main activity add: u will get global static shared preferences object

 companion object {    
    lateinit var sharedPreferences: SharedPreferences
}

override fun onCreate(savedInstanceState: Bundle?) {
 sharedPreferences = applicationContext.getSharedPreferences(
        SHARED_PREFERENCE_NAME,
        Context.MODE_PRIVATE
    )
Bartosz Kolej
  • 97
  • 1
  • 12
2

Try using default preferences with an Application context. A context is similar to the environment an application runs in on linux or windows (e.g. environment variables like PATH windowing style or console size). Each Activity and Service has its own Context too for example screen orientation, theme, and label, etc. but for your application you don't want the context of the Activity, you want something global to the app, this is where context.getApplicationContext() is useful. This the same throughout the app and will always give you the same default preferences.

Dan S
  • 9,139
  • 3
  • 37
  • 48
  • Can you elaborate? I tried `SharedPreferences prefs = getDefaultSharedPreferences(this);` but it doesn't work. – Jake Wilson Sep 20 '11 at 20:29
  • Use `PreferenceManager.getDefaultSharedPreferences(applicationContext);` no matter where you are in the code it requires a context to use the Preferences. – Dan S Sep 20 '11 at 21:29
  • 1
    @DanS - And where do you expect him to get the applicationContext from when he is having an issue just getting the context ? – Bamerza Nov 14 '14 at 00:05
  • @Bamerza As I said a `Context` is required and other answers show how to store a `Context` in a static fashion. – Dan S Nov 14 '14 at 00:29
1

use this code to a new class.

import android.content.Context;
import android.content.SharedPreferences;

/**
   * Created by Atiar Talukdar on 6/5/2017.
*/

public class TemporaryStorageSharedPreference {
protected final static int DEFAULT = 0;
int temp = 0;

public int readSharedPreference(Context context, String spName,String key){
    SharedPreferences sharedPreferences = context.getSharedPreferences(spName, Context.MODE_PRIVATE);
    return temp = sharedPreferences.getInt(key,DEFAULT);
}

public void writeSharedPreference(Context context,String ammount,String spName,String key ){

    SharedPreferences sharedPreferences = context.getSharedPreferences(spName, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putInt(key, DEFAULT);
    editor.commit();
}
}
Atiar Talukdar
  • 668
  • 11
  • 22
1

In Kotlin you can do this:

val myClass = MyClass(this)

Now this is how you can get context in class

class MyClass(context: Context) {

    val context: Context = context

}

Now to get Shared Preferences with context you can do this:

context.getSharedPreferences(...)
Zohab Ali
  • 8,426
  • 4
  • 55
  • 63
0

First, declare a private attribute in your class. In my case, I have a BaseAdapter class:

private final Context ctx;
private final Vector<Acto> actos;

public ActoAdaptador(Context ctx, Vector<Acto> as) {
    super();
    this.ctx = ctx;
    this.actos = as;
}

Then, when to use the SharedPreferences:

ctx.getSharedPreferences("com.joninazio.euskofest.UsingPreferences_preferences", Context.MODE_PRIVATE)

That way works for me at least :)

joninx
  • 1,775
  • 6
  • 31
  • 59
0

create SharedPreferences class

 /**
     * @param mContext
     * @param key
     * @param value
     */
    public static void savePreferences(Context mContext, String key, String value) {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(key, value).apply();
    }

    /**
     * @param context
     * @param keyValue
     * @return
     */
    public static String getPreferences(Context context, String keyValue) {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
        return sharedPreferences.getString(keyValue, "");
    }

    /**
     * @param mContext
     */
    public static void removeAllSharedPreferences(Context mContext) {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.clear().apply();
    }
Mohsinali
  • 543
  • 7
  • 14
0

Use this code to get the context from activity.

if (context != null) {
    SharedPreferences sharedPrefs = context.getSharedPreferences("YOUR.PACKAGE.NAME", MODE_PRIVATE);
}
Son Truong
  • 13,661
  • 5
  • 32
  • 58
M. H.
  • 960
  • 11
  • 13
-1

For Kotlin and for default preference file, you can use the following code:

val sharedPref = activity?.getPreferences(Context.MODE_PRIVATE)
Thodoris
  • 55
  • 2
  • 10