How to set a default value to SharedPreferences programmatically?

后端 未结 2 1946
南方客
南方客 2021-01-15 04:02

I am using SharedPreferences to keep the information about user\'s weight, which I need in my application. The problem is, how to set a default value (eg. 75 kg) automatical

2条回答
  •  粉色の甜心
    2021-01-15 04:19

    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).

提交回复
热议问题