先看一下Google官方對於SharedPreferences的定義:
The SharedPreferences class provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types. You can use SharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings. This data will persist across user sessions (even if your application is killed).
SharedPreferences可以用來永久地存儲數據,即使應用被銷毀。事實上數據存儲在Android的內部存儲器上。
有兩種分方法用來獲取SharedPreferences對象。 getSharedPreferences() - 當應用需要多個由名字區分的存儲文件時,可以調用這個方法。getPreferences()-當應用只需要一個存儲文件時,調用這個方法。
在SharedPreferences對象中寫入數據,需要:
1.調用edit()方法獲得一個SharedPreferences.Editor對象。
2.使用Editor對象的方法比如putBoolean()和putString()等將數據寫入Editor。
3.使用Editor對象的方法commit()或apply()將數據提交。
讀取SharedPreferences中的數據只需要調用SharedPreferences的方法如getBoolean()和getString().
下面是一個使用SharedPreferences存儲數據的例子。
public class Calc extends Activity { public static final String PREFS_NAME = "MyPrefsFile"; @Override protected void onCreate(Bundle state){ super.onCreate(state); . . . // Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); boolean silent = settings.getBoolean("silentMode", false); setSilent(silent); } @Override protected void onStop(){ super.onStop(); // We need an Editor object to make preference changes. // All objects are from android.context.Context SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("silentMode", mSilentMode); // Commit the edits! editor.commit(); } }
從Google的介紹中可以看到,SharedPreferences的局限性在於只能存儲基本類型:boolean,floot,short,int,long,string等。對於用戶自定義的類型,通常由多個基本類型數據和數組組成。比如這樣一個自定義類型:
public class Action { // Action Data private UUID id; private Date start;private String actionName; private int alarmingHour=0;private String[] records = new String[100]; }
這時候就不能使用SharedPreferences來存儲。
這個時候就需要另一個主角 :JSON.
JSON的全稱是JavaScript對象表示法,是存儲和交換文本信息的語法,類似 XML,實現了對象與文本之間的轉化。
在Android中內置了JSONObject和JSONArray.
對於這樣一個用戶自定義類型,可以通過
/** * transform the Action instance to JSONObject,and then save JSONObject.toString() * to SharedPreference. * @return the JSONObject corresponding to the Action * @throws JSONException */ public JSONObject toJSON() throws JSONException{ JSONObject json = new JSONObject(); json.put(JSON_id,id.toString()); json.put(JSON_startDate, start.getTime()); JSONArray array = new JSONArray(); JSONObject JSONRecords[] = new JSONObject[length]; for(int i = 0; i<length;i++){ JSONRecords[i] = new JSONObject(); JSONRecords[i].put(JSON_record, records[i].getRecord()); array.put(i,JSONRecords[i]); } json.put(JSON_dailyRecords,array); return json; } /** * get the Action from JSONObject * @param jsonString the jsonString retrieved from SharedPreference. * @return the Action stored in JSONObject * @throws JSONException */ public static Action parseJSONString(String jsonString) throws JSONException{ JSONObject json; json = new JSONObject(jsonString); UUID id = UUID.fromString(json.getString(JSON_id)); Date start = new Date(json.getLong(JSON_startDate)); String actionName = json.getString(JSON_name); String[] dailyRecords = new DailyRecord[100]; for (int i = 0; i<100;i++){ JSONObject json_record = array.getJSONObject(i); String record = json_record.getString(JSON_record); dailyRecords[i] = record; } return new Action(id,start,actionName,dailyRecords); }
來實現Action和JSONObject之間的轉換,JSONObject實際是是文本的形式,可以很方便地轉化為String,因此使用SharedPreferences來存儲轉換之后的String就可以實現Action的存儲。
SharedPreferences sp =getSharedPreferences(Config.CurrentAction, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); try { editor.putString(Config.CurrentActionDetails, currentAction.toJSON().toString()); } catch (JSONException e) { e.printStackTrace(); } editor.apply();
從SharedPreferences中讀取Action可以這樣做:
try { SharedPreferences sp = getSharedPreferences(Config.CurrentAction, Context.MODE_PRIVATE); String jsonString = sp.getString(Config.CurrentActionDetails, ""); currentAction = Action.parseJSONString(jsonString); } catch (JSONException e) { e.printStackTrace(); }
這樣就實現了用戶自定義類Action的本地存儲與讀取。
