Shared Preferences in android showing Default value not found

前端 未结 4 1332
滥情空心
滥情空心 2021-01-25 15:14

I strucked in storing and getting shared preferences.When a user has been registered if that registration is success then that values has to be stored in his profile nothing but

4条回答
  •  遇见更好的自我
    2021-01-25 15:58

    try something like this.. Create a class

    public class SharedPreferenceCustom {
      private Context mContext;
      private String defValue = "";
    
      public SharedPreferenceCustom(Context context) {
        this.mContext = context;
      }
    
      public void setSharedPref(String inputKey, Object inputValue) {
        final SharedPreferences sharedPreferences = mContext.getSharedPreferences("a2a", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(inputKey, String.valueOf(inputValue));
        editor.apply();
    
        }
    
      public String getSharedPref(String inputKey) {
        SharedPreferences sharedPreferences = mContext.getSharedPreferences("a2a", Context.MODE_PRIVATE);
        return sharedPreferences.getString(inputKey, defValue);
     }
    }
    

    and call whenever needed

    Call by

       SharedPreferenceCustom sp = new SharedPreferenceCustom(mContext);
       sp.setSharedPref("KEY", "VALUE");
       // or
       sp.getSharedPref("KEY");
    

提交回复
热议问题