20

I have a user preference in my app, which gets used by different activities. I would like to know the best way to utilize those preferences between different activities in my App.

I have this idea to create a shared preference object from the main activity and from there send intents to the different activities to take actions. Would that work...?

Or just keep calling getsharedpreferences() from every activity..?

Thanks.

eRaisedToX
  • 3,221
  • 2
  • 22
  • 28
irobotxx
  • 5,963
  • 11
  • 62
  • 91

4 Answers4

26

Sending shared preferences through intents seems overcomplicated. You could wrap the shared preferences with something like the below and call the methods directly from your activities:

public class Prefs {
    private static String MY_STRING_PREF = "mystringpref";
    private static String MY_INT_PREF = "myintpref";

    private static SharedPreferences getPrefs(Context context) {
        return context.getSharedPreferences("myprefs", 0);
    }

    public static String getMyStringPref(Context context) {
        return getPrefs(context).getString(MY_STRING_PREF, "default");
    }

    public static int getMyIntPref(Context context) {
        return getPrefs(context).getInt(MY_INT_PREF, 42);
    }

    public static void setMyStringPref(Context context, String value) {
        // perform validation etc..
        getPrefs(context).edit().putString(MY_STRING_PREF, value).commit();
    }

    public static void setMyIntPref(Context context, int value) {
        // perform validation etc..
        getPrefs(context).edit().putInt(MY_INT_PREF, value).commit();
    }
}
fornwall
  • 2,877
  • 3
  • 25
  • 38
  • hmm.. too many choices here. but actually my user preference contains checkboxes that performs action in a listview. so i might go with the suggestions here. only problem is that its populating from a customCursorAdapter, so jjst figuring out where to call it – irobotxx Oct 29 '10 at 13:15
  • 1
    yeah.. it works, would have really shot myself in the foot if i had gone through the intent route! – irobotxx Oct 29 '10 at 14:28
  • Have you faced a performance issue using this approach ? because I am using the same approach and I have performance issue but not sure if this approach is the cause of the problem – AlAsiri Jan 06 '13 at 23:13
  • If you have a lot of prefs you will want to batch them. If you are targetting android 2.3 or newer you should probably use the non-blocking apply() method instead of commit() - http://developer.android.com/reference/android/content/SharedPreferences.Editor.html#apply(). – fornwall Jan 07 '13 at 13:17
  • Why don't you just declare the whole class as `static`? – Fred Feb 01 '14 at 22:17
8

You can use this way and declare same variables with same name in all activites where you want to use.

  public static final String PREFS_NAME = "MyPrefsFile";
  static SharedPreferences settings;
  SharedPreferences.Editor editor;
  int wordCount;

 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    settings = getSharedPreferences(PREFS_NAME, 0);
    editor = settings.edit();

    wordCount = settings.getInt("wordCount", 4); 

  }

Here initially wordCount will give 4; And when you edit wordCount and want to store again

  editor.putInt("wordCount", 6);
  editor.commit();

You have to declare this same variables in activities where you want to use shared preferences. And its better you call getSharedPreferences in every activity.

I don't think that passing that preference in intent will work.

krunal shah
  • 16,089
  • 25
  • 97
  • 143
0

You can of course use shared preferences in your applications.

If you have more than a simple type than string or int, you can use a singleton or extends the application class which will be accessible by all activities of your application. => No disk access here. Simply kept in memory.

William Remacle
  • 1,480
  • 2
  • 16
  • 24
0

Here's a nice & easy solution in Kotlin – 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) }
    }
}
Jeehut
  • 20,202
  • 8
  • 59
  • 80
  • why you did not use `commit()` or `appyl()`? – Kuvonchbek Yakubov Jun 17 '20 at 17:06
  • @KuvonchbekYakubov Good question, I don't remember. It probably worked like this but maybe it's wrong? Feel free to report or provide a fixed version (e.g. via GitHub Gists) and I'll update my answer! :) – Jeehut Jun 18 '20 at 12:56