How to set a default value to SharedPreferences programmatically?

后端 未结 2 1945
南方客
南方客 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

    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);
    
        }
    }
    

提交回复
热议问题