資料存儲在開發中是使用最頻繁的,在這裡主要介紹Android平台中實作資料存儲的5種方式,分别是:
1 使用SharedPreferences存儲資料
2 檔案存儲資料
3 SQLite資料庫存儲資料
4 使用ContentProvider存儲資料
5 網絡存儲資料
如果想了解檔案存儲了解上一篇 Android 資料存儲之 檔案存儲
這一篇我們來了解下共享參數是怎麼回事。說白了共享參數就是比較輕量級别的存儲方式,比如存儲一些視窗一些配置資訊和使用者的賬号和密碼等資訊的存儲。
它是什麼樣的處理方式呢? SharedPreferences類似過去Windows系統上的ini配置檔案,但是它分為多種權限,可以全局共享通路,android123提示最終是以xml方式來儲存,整體效率來看不是特别的高,對于正常的輕量級而言比SQLite要好不少,如果真的存儲量不大可以考慮自己定義檔案格式。xml 處理時Dalvik會通過自帶底層的本地XML Parser解析,比如XMLpull方式,這樣對于記憶體資源占用比較好。
它的本質是基于XML檔案存儲key-value鍵值對資料,通常用來存儲一些簡單的配置資訊。
其存儲位置在/data/data/<包名>/shared_prefs目錄下。
SharedPreferences對象本身隻能擷取資料而不支援存儲和修改,存儲修改是通過Editor對象實作。
實作SharedPreferences存儲的步驟如下:
一、根據Context擷取SharedPreferences對象
二、利用edit()方法擷取Editor對象。
三、通過Editor對象存儲key-value鍵值對資料。
四、通過commit()方法送出資料。
讀取方式代碼如下:
public boolean saveData(String name, int age){
boolean flage = false;
//MODE_PRIVATE
//MODE_WORLD_READABLE
//MODE_WORLD_WRITEABLE
//MODE_MULTI_PROCESS
SharedPreferences preferences= context.getSharedPreferences("userInfo", Context.MODE_PRIVATE);
//1.Call edit() to get a SharedPreferences.Editor.
SharedPreferences.Editor editor = preferences.edit();
//2. Add values with methods such as putBoolean() and putString().
editor.putString("name", name);
editor.putInt("age", age);
//3 Commit the new values with commit()
flage=editor.commit();
return flage;
}
public Map<String, Object> getSharedPerferencesData(){
Map<String, Object> map = new HashMap<String, Object>();
SharedPreferences preferences= context.getSharedPreferences("userInfo", Context.MODE_PRIVATE);
String name= preferences.getString("name", "");
int age = preferences.getInt("age", 0);
map.put("name", name);
map.put("age", age);
return map;
}
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIyVGduV2QvwVe0lmdhJ3ZvwFM38CXlZHbvN3cpR2Lc1TPB10QGtWUCpEMJ9CXsxWam9CXwADNvwVZ6l2c052bm9CXUJDT1wkNhVzLcRnbvZ2LcZXUYpVd1kmYr50MZV3YyI2cKJDT29GRjBjUIF2LcRHelR3LcJzLctmch1mclRXY39DN0IzM0kTM0EDMyATM2EDMy8CX0Vmbu4GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)