Android簡易數據存儲之SharedPreferences


  Andorid提供了多種數據存儲的方式,例如前面說到的“Android數據存儲之SQLite的操作”是用於較復雜的數據存儲。然而,如果有些簡單的數據存儲如果采用SQLite的方式的話會顯得比較笨重。例如:記錄用戶是否訪問過APP的歡迎頁面之類的數據,如果采用SQLite的話會顯得沒必要而且費時費力。因此Andorid提供了另一種存儲簡單數據的方式SharedPreferences。SharedPreferences是一個輕量級的數據存儲方式,其僅支持boolean、int、long、float、String和Set<String>這幾種數據類型。

  

  此外,SharedPreferences不能直接添加和修改數據,添加和修改數據需要通過SharedPreferences的Editor來完成。具體的實現可參考官方文檔:http://developer.android.com/reference/android/content/SharedPreferences.html。下面看看SharedPreferences是如何進行添加、修改和讀取數據的。

  新建一個工程,名字為DataOperate,然后再MainActivity.java中添加如下代碼

        SharedPreferences sharedPreferences = getSharedPreferences("appSetting", MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putBoolean("IsFirstView", false);
        editor.putString("AppName", "SharePreferences Demo");
        editor.commit();//同步提交到磁盤文件,因而會出現阻塞等的現象,如果要確保提交成功,盡量使用commit
        editor.apply();//先提交到內存,然后異步提交到磁盤,效率更高,但沒有返回消息。

        Boolean isFirstView = sharedPreferences.getBoolean("IsFirstView", false);
        System.out.println("IsFirstView : " + isFirstView);
        String appName = sharedPreferences.getString("AppName", "");
        System.out.println("AppName : " + appName);
        String author = sharedPreferences.getString("author", "author null");
        System.out.println("Author : " + author);

  將APP運行到模擬器中,可以看到如下的輸出結果:

09-12 10:34:50.627    2669-2669/com.example.ibm.dataoperate I/System.out﹕ IsFirstView : false
09-12 10:34:50.627    2669-2669/com.example.ibm.dataoperate I/System.out﹕ AppName : SharePreferences Demo
09-12 10:34:50.651    2669-2669/com.example.ibm.dataoperate I/System.out﹕ Author : author null

  這就是SharedPreferences的簡單應用。然而,這里有幾個地方需要注意的:

  1、文件創建或讀取的方式有三種:MODE_PRIVATEMODE_WORLD_READABLEMODE_WORLD_WRITEABLE

    然而官方推薦的使用方式為MODE_PRIVATE的使用方式,也是默認的方式。至於原因,官方文檔是這么說的:

This constant was deprecated in API level 17.
Creating world-readable files is very dangerous, and likely to cause security holes in applications. It is strongly discouraged; instead, applications should use more formal mechanism for interactions such as ContentProvider, BroadcastReceiver, and Service. There are no guarantees that this access mode will remain on a file, such as when it goes through a backup and restore. File creation mode: allow all other applications to have read access to the created file.

  MODE_WORLD_READABLE和MODE_WORLD_WRITEABLE都是very dangerous的,如果采用了這兩種方式都會導致應用存在安全漏洞。因此官方推薦使用的MODE_PRIVATE的方式。

  2、Editor提交數據的方式有兩種。一種是通過commit的方式提交,另一種是通過apply的方式來提交。

  官方文檔是這么說的:

Commit your preferences changes back from this Editor to the SharedPreferences object it is editing. This atomically performs the requested modifications, replacing whatever is currently in the SharedPreferences.

Note that when two editors are modifying preferences at the same time, the last one to call apply wins.

Unlike commit(), which writes its preferences out to persistent storage synchronously, apply() commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk and you won't be notified of any failures. If another editor on this SharedPreferences does a regular commit() while a apply() is still outstanding, the commit() will block until all async commits are completed as well as the commit itself.

As SharedPreferences instances are singletons within a process, it's safe to replace any instance of commit() with apply() if you were already ignoring the return value.

You don't need to worry about Android component lifecycles and their interaction with apply() writing to disk. The framework makes sure in-flight disk writes from apply() complete before switching states.

The SharedPreferences.Editor interface isn't expected to be implemented directly. However, if you previously did implement it and are now getting errors about missing apply(), you can simply call commit() from apply().

  這兩種提交方式的不同點在於(英文不好,有錯請指出):

    a、apply是先將數據提交到內存,然后異步寫入文件,效率較高;而commit是同步提交到內存並寫入文件,因此效率相對較低,如果數據大的話會存在阻塞的情況。

    b、由於apply是使用異步提交的方式,因此沒有返回值,即使寫入失敗也不會返回消息。而commit有返回值,能確保數據正常寫入磁盤文件。因此如果需要確保數據寫入的完整性,最好采用commit的方式。

  3、數據存儲方式和位置

    成功運行APP后,可以在app安裝目錄下的shared_prefs(完整路徑為/data/data/項目包/shared_prefs/名稱.xml)中看到“appSetting.xml”(文件名為自定義的名稱),打開xml文件后可以看到其實就是采用了標准xml文件鍵值對的方式進行存儲。

  存儲位置:

  文件內容:

  4、PreferenceActivity創建配置首選項界面

    此外Android還提供了PreferenceActivity快速創建首選項頁面。和SharedPreferences不同的是,SharedPreferences是純操作,要另外創建設置頁面;而PreferenceActivity則可以讓你快速地創建設置界面和存儲數據。在此先不深入說明,改天有空再另寫一篇文章加以描述。感興趣的可以在查看官方文檔:http://developer.android.com/reference/android/preference/PreferenceActivity.html。牆哦!俗話說。。。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM