How to save data by using SharedPreferences in a Fragment

前端 未结 1 1303
刺人心
刺人心 2021-01-29 16:51
  1. I\'m having a problem with saving data permanently. It should be simple, I\'m sending data to another Fragment and it works perfectly, however, I have no idea how to save
1条回答
  •  迷失自我
    2021-01-29 17:13

    If you want to use Shared Preferences instead of sending the data through bundles, use this code:

        String stringToSave = "Save me!";
    
        // To save data to SP
        SharedPreferences.Editor editor = getContext().getSharedPreferences(SHARED_NAME_STRING, MODE_PRIVATE).edit();
        editor.putString(USER_NAME_STRING, stringToSave);
        editor.apply();
    
        // To load the data at a later time
        SharedPreferences prefs = getContext().getSharedPreferences(SHARED_NAME_STRING, MODE_PRIVATE);
        String loadedString = prefs.getString(USER_NAME_STRING, null);
    

    This code is setup to work with fragments. If you use an Activity instead, remove getContext() in front of getSharedPreferences().

    0 讨论(0)
提交回复
热议问题