SharedPreferences詳解

咱們在開發軟件的時候,常須要向用戶提供軟件參數設置功能,例如咱們經常使用的微信,用戶能夠設置是否容許陌生人添加本身爲好友.對於軟件配置參數的保存,若是是在window下一般咱們會採用ini文件進行保存.若是是J2EE下面,咱們會採用properties屬性文件或者xml進行保存.在咱們的Android應用中又適合採用什麼方式保存軟件配置參數呢?Android平臺給咱們提供了一個SharedPreferences類,它是一個輕量級應用程序內部輕量級的存儲方案,特別適合用於保存軟件配置參數,好比boolean,int,float,long,String等數據.使用SharedPreferences保存數據,其實質是採用了xml文件存放數據,路徑爲:/data/data/<package name>/shared_prefs.web

獲取SharedPreferences的兩種方式:微信

1 調用Context對象的getSharedPreferences()方法spa

2 調用Activity對象的getPreferences()方法orm

兩種方式的區別:xml

調用Context對象的getSharedPreferences()方法得到的SharedPreferences對象能夠被同一應用程序下的其餘組件共享.對象

調用Activity對象的getPreferences()方法得到的SharedPreferences對象只能在該Activity中使用.開發

 

SharedPreferences的四種操做模式:get

Context.MODE_PRIVATEit

Context.MODE_APPENDimport

Context.MODE_WORLD_READABLE

Context.MODE_WORLD_WRITEABLE

 

Context.MODE_PRIVATE:爲默認操做模式,表明該文件是私有數據,只能被應用自己訪問,在該模式下,寫入的內容會覆蓋原文件的內容

Context.MODE_APPEND:模式會檢查文件是否存在,存在就往文件追加內容,不然就建立新文件.

Context.MODE_WORLD_READABLE和Context.MODE_WORLD_WRITEABLE用來控制其餘應用是否有權限讀寫該文件.

MODE_WORLD_READABLE:表示當前文件能夠被其餘應用讀取.

MODE_WORLD_WRITEABLE:表示當前文件能夠被其餘應用寫入.

將數據保存至SharedPreferences:

SharedPreferences preferences=getSharedPreferences("user",Context.MODE_PRIVATE);

Editor editor=preferences.edit();

String name="xixi";

String age="22";

editor.putString("name", name);

editor.putString("age", age);

editor.commit();

 

從SharedPreferences獲取數據:

SharedPreferences preferences=getSharedPreferences("user", Context.MODE_PRIVATE);

String name=preferences.getString("name", "defaultname");

String age=preferences.getString("age", "0");

相關文章
相關標籤/搜索