SharedPreferences儲存簡單的封裝單例拿去用
阿新 • • 發佈:2021-01-23
技術標籤:andorid
public class SharedPreferencesDanLi { private String filename; private Context context; private android.content.SharedPreferences SharedPreferences; public SharedPreferencesDanLi(String filename, Context context) { this.filename = filename; this.context = context; SharedPreferences=context.getSharedPreferences(filename, Context.MODE_PRIVATE); } private static SharedPreferencesDanLi sharedPreferencesDanLi; //提供一個公共的、靜態的、返回值型別是當前本類的物件 public static SharedPreferencesDanLi getSharedPreferencesDanLi(String filename, Context context){ if(sharedPreferencesDanLi == null){ synchronized (SharedPreferencesDanLi.class){ if(sharedPreferencesDanLi == null) { sharedPreferencesDanLi = new SharedPreferencesDanLi(filename,context); } } } return sharedPreferencesDanLi; } public void putVules(String key,Object o){ SharedPreferences.Editor editor = SharedPreferences.edit(); //如果是字元型型別 if (o instanceof String) { editor.putString(key, o.toString()).commit(); } //如果是int型別 if (o instanceof Integer) { editor.putInt(key, Integer.parseInt(o.toString())).commit(); } //如果是Long型別 if (o instanceof Long) { editor.putLong(key, Long.parseLong(o.toString())).commit(); } //如果是布林型別 if (o instanceof Boolean) { editor.putBoolean(key, Boolean.parseBoolean(o.toString())).commit(); } } //獲取資料的方法 public String getString(String key) { return SharedPreferences.getString(key, null); } public boolean getBoolean(String key) { return SharedPreferences.getBoolean(key, false); } public int getInt(String key) { return SharedPreferences.getInt(key, -1); } public long getLong(String key) { return SharedPreferences.getLong(key, -1); } //清除當前檔案的所有的資料 public void clear() { SharedPreferences.edit().clear().commit(); } }
使用教程:存入
SharedPreferencesDanLi uss = SharedPreferencesDanLi.getSharedPreferencesDanLi("token", MainActivity.this);
uss.putVules("token儲存的健","要儲存的值");
那開始取出把:
SharedPreferencesDanLi uss = SharedPreferencesDanLi.getSharedPreferencesDanLi("uss", MainActivity.this); String token=uss.getString("token儲存的健");
單例大家都會用直接用就好了親測實戰中使用,歡迎萌新參考,歡迎大佬指點。