Shared Preferences reset data when app is force closed or device is restarted

后端 未结 6 1888
暖寄归人
暖寄归人 2020-11-30 11:21

I\'m developing an application in which I\'m storing username and password in SharedPreferences. All things are working fine for me, s

6条回答
  •  北海茫月
    2020-11-30 12:15

    Hi ! Solution that worked for me!

    Solution 1 Solution 2

    Solution 1:

      SharedPreferences sharedPreferences = getSharedPreferences("namefile",               
        Context.MODE_PRIVATE);//store or retrieved file "namefile.xml".
        /*or 
       SharedPreferences sharedPreferences    
       =getActivity().getSharedPreferences("namefile", Context.MODE_PRIVATE); 
       (use Shared Preferences in Fragment)*/
       String getValueFromKey = sharedPreferences.getString("yourKey",new   
       String());
       //Log.d("printf:",getValueFromKey );
       getValueFromKey ="Hahaha"; /*  Edit value    
       or Do nothing …… */
       SharedPreferences.Editor editor = sharedPreferences.edit();
       editor.clear(); //[important] Clearing your editor before using it.
       editor.putString("yourKey", getValueFromKey);
       editor.commit();
    

    Solution 2:

    SharedPreferences sharedPreferences = getSharedPreferences("namefile",     
      Context.MODE_PRIVATE);//store or retrieved file "namefile.xml".
    /*or 
    SharedPreferences sharedPreferences = 
    getActivity().getSharedPreferences("namefile", Context.MODE_PRIVATE); 
    (use Shared Preferences in Fragment)
    */
    Set getListValueFromKey =
    sharedPreferences.getStringSet("yourKey",new HashSet());
    getListValueFromKey.add("Hahaha");
    getListValueFromKey.add("Kakaka");
    getListValueFromKey.add("Hohoho");
    /*  Add value or Do nothing …… */
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.clear(); //[important] Clearing your editor before using it.
    editor.putStringSet("yourKey", getListValueFromKey);
    editor.commit();
    

    I have had exactly same problem like yours and this worked for me. For my whole code sample see

提交回复
热议问题