一、概述
SharedPreferences是一種輕量級的資料存盤方式,采用鍵值對的存盤方式,
SharedPreferences只能存盤少量資料,大量資料不能使用該方式存盤,支持存盤的資料型別有booleans, floats, ints, longs, and strings,
SharedPreferences存盤到一個XML檔案中的,路徑在/data/data//shared_prefs/下,檔案名以及存盤后面詳細講述,
二、基本用法
1.獲取SharedPreferences物件
要創建存盤檔案或訪問已有資料,首先要獲取SharedPreferences才能進行操作,獲取SharedPreferences物件有下面兩個方式:
(1)getSharedPreferences(String name, int mode) — 通過Context呼叫該方法獲得物件,它有兩個引數,第一個name 指定了SharedPreferences存盤的檔案的檔案名,第二個引數mode 指定了操作的模式,這種方式獲取的物件創建的檔案 可以被整個應用所有組件使用,有指定的檔案名,
(2)getPreferences(int mode) — 通過Activity呼叫獲得物件,它只有一個引數mode 指定操作模式,這種方式獲取的物件創建的檔案 屬于Activity,只能在該Activity中使用,且沒有指定的檔案名,檔案名同Activity名字,
操作模式(mode):
兩個方式都有一個mode引數,mode具體有4個值,最新的只能使用默認模式 Context.MODE_PRIVATE,
Context.MODE_PRIVATE(0):默認模式,創建的檔案只能由 呼叫的應用程式(或者共享相同用戶ID的應用程式)訪問,
2.資料更新
SharedPreferences添加或更新資料,通過SharedPreferences 獲取 SharedPreferences.Editor,操作檔案資料,最后通過commit()或apply()提交修改,
public static boolean putString(final Context context, final String key, final String pValue) {
final SharedPreferences.Editor editor = PreUtils.getSharedPreferences(context).edit();
editor.putString(key, pValue);
return editor.commit();
}
commit()和apply()區別:
apply()立即更改記憶體中的SharedPreferences物件,但異步地將更新寫入磁盤,commit()同步地將資料寫入磁盤,commit()是同步的,在主執行緒呼叫它應該多注意,因為可能引起阻塞,引起ANR,
commit()有回傳值,回傳是否成功寫入永久性存盤種,apply()沒有回傳值,
3.資料獲取,
public static String getString(final Context context, final String key, final String defaultValue) {
return PreUtils.getSharedPreferences(context).getString(key, defaultValue);
}
參考原文地址鏈接:
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/293642.html
標籤:其他
上一篇:Room使用
