android default values for shared preferences

空扰寡人 提交于 2019-12-01 17:47:07
Tobiel

Simple, if you want a separate default value for each variable, you need to do it for each one, but on your method:

 public String get(String key) {
    return this.sharedPreferences.getString(key,"this is your default value");
}

If the variable was never accessed by the user or was never created, the system will set the default value as value and if you or the user changed this value, the default value is ignored. See http://developer.android.com/guide/topics/data/data-storage.html#pref

Directly from the Android Documentation:

The SharedPreferences class provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types. You can use SharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings. This data will persist across user sessions (even if your application is killed).

Could you use the default value parameter of the getX() method?

For example, to get a String called 'username', you could use this:

String username = prefs.getString("username_key", "DefaultUsername");

You can simply define your default values in your Preferences class.

You can store default values in string resource:

<string name="key_name">default_value</string>

and then get it as it follows:

int ResId = context.getResources().getIdentifier(key_name, "string", context.getPackageName()));
prefs.getString(key_name,context.getResources().getString(ResId);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!