How to set a default value to SharedPreferences programmatically?

情到浓时终转凉″ 提交于 2019-12-01 10:41:32

Try this way, please.

        SharedPreferences prefs = getActivity().getSharedPreferences(
                PREFS_NAME, 0);
        if (prefs.getInt("key_weight", null) == null) {
            Editor editor = prefs.edit();
            editor.putInt("key_weight", 75);
            editor.commit();
        }

For first time use this, or else use your code only(means without if condition).

getInt takes a default value.

prefs.getInt("key_weight", 75)

Or in a more mainstream style....

public class AppPreferences {

    private SharedPreferences mPreferences;

    Public AppPreferences(SharedPreferences preferences)
    {
         this.mPreferences = preferences;
    }

    private static final String KEY_WEIGHT_KEY = "key_weight";
    private static final int DEFAULT_KEY_WEIGHT = 75;

    public static  int getKeyWeight()
    {
      return mPreferences.getInt(KEY_WEIGHT_KEY,DEFAULT_KEY_WEIGHT);

    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!