個人感覺好用的sharedpreference工具類寫法
阿新 • • 發佈:2019-01-28
** * 2017/5/9 13:53 * Created by jiangchen * 作用:sharedpreference工具類 */ public class SharedPreferenceHelper { private static final String SHAREDPREFENCE_NAME = "mysp"; //SP名 /** *2017/5/9 13:57 *Created by jiangchen *作用:這樣所有要儲存的資料都寫上面,然後下面寫save,get方法,可以更直白的知道你存了哪些資料 */ private finalString LOGIN_ID = "id"; //所存ID private final String LOGIN_PSW = "psw"; //所村密碼 Context context; private static SharedPreferenceHelper sharedPreferenceHelper; private SharedPreferenceHelper(Context context) { this.context = context;} /** * 2017/5/9 13:53 * Created by jiangchen * 作用:單例模式,獲取例項 */ public static SharedPreferenceHelper getInstance(Context context) { if (sharedPreferenceHelper == null) { sharedPreferenceHelper = new SharedPreferenceHelper(context); } return sharedPreferenceHelper; } /** 補充註釋 ---- 時間: 補充人:jiangchen * 儲存ID,取ID */ public void saveLoginId(String id) { SharedPreferences sp = context.getSharedPreferences(SHAREDPREFENCE_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.putString(LOGIN_ID, id); editor.commit(); } public String getLoginId() { SharedPreferences sp = context.getSharedPreferences(SHAREDPREFENCE_NAME, Context.MODE_PRIVATE); return sp.getString(LOGIN_ID, ""); } /** 補充註釋 ---- 時間: 補充人:jiangchen * 儲存密碼,取密碼 */ public void saveLoginPsw(String id) { SharedPreferences sp = context.getSharedPreferences(SHAREDPREFENCE_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.putString(LOGIN_PSW, id); editor.commit(); } public String getLoginPsw() { SharedPreferences sp = context.getSharedPreferences(SHAREDPREFENCE_NAME, Context.MODE_PRIVATE); return sp.getString(LOGIN_PSW, ""); } }