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.
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.
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.
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.
Yes you can maintain as many shared preference files for an app as you can.
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With