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_PRIVATE、
MODE_WORLD_READABLE和
MODE_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。墙哦!俗话说。。。