Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the Best way to use shared preferences between activities

Tags:

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.

like image 340
irobotxx Avatar asked Oct 29 '10 12:10

irobotxx


People also ask

What are shared preferences and how do you use it?

Shared Preferences allow you to save and retrieve data in the form of key,value pair. In order to use shared preferences, you have to call a method getSharedPreferences() that returns a SharedPreference instance pointing to the file that contains the values of preferences.

How do I access shared preferences?

These preferences will automatically save to SharedPreferences as the user interacts with them. To retrieve an instance of SharedPreferences that the preference hierarchy in this activity will use, call getDefaultSharedPreferences(android. content. Context) with a context in the same package as this activity.

How are shared preferences stored?

Android Shared Preferences Overview Android stores Shared Preferences settings as XML file in shared_prefs folder under DATA/data/{application package} directory. The DATA folder can be obtained by calling Environment.

Can an app have multiple shared pref files?

Yes you can maintain as many shared preference files for an app as you can.


1 Answers

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();
    }
}
like image 118
fornwall Avatar answered Sep 24 '22 08:09

fornwall