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。墙哦!俗话说。。。

Android简易数据存储之SharedPreferences的更多相关文章

  1. Android中数据存储之SharedPreferences

    import android.content.Context; import android.content.SharedPreferences; import android.content.Sha ...

  2. Android之数据存储之SharedPreferences

    SharedPreferences是以键值对形式存储数据,主要用于记录系统的设置,如飞行模式是否开启,声音大小的值等.//SharedPreferences方式保存到xml文件SharedPrefer ...

  3. Android数据存储-通过SharedPreferences实现记住密码的操作

    在Android中登陆中,为了实现用户的方便,往往需要根据用户的需要进行记住密码的操作,所以,在Android数据存储中SharedPreferences恰恰可以实现这一点 下面,小编将带领大家通过S ...

  4. Android 数据存储之 SharedPreferences储存

    ------------------------------------------SharedPreferences存储--------------------------------------- ...

  5. Android开发手记(16) 数据存储一 SharedPreferences

    Android为数据存储提供了五种方式: 1.SharedPreferences 2.文件存储 3.SQLite数据库 4.ContentProvider 5.网络存储 SharedPreferenc ...

  6. Android数据存储三剑客——SharedPreferences、File、SQLite

    Android中常用的数据存储一般有三种方式:SharedPreferences.文件和SQLite数据库,用来保存需要长时间保存的数据.本文将通过几个具体的小实例来讲解这三种方式的具体实现. 数据存 ...

  7. Android中数据存储(一)

    国庆没有给国家添堵,没有勾搭妹子,乖乖的写着自己的博客..... 本文将为大家介绍Android中数据存储的五种方式,数据存储可是非常重要的知识哦. 一,文件存储数据 ①在ROM存储数据 关于在ROM ...

  8. android学习笔记45——android的数据存储和IO

    android的数据存储和IO SharedPreferences与Editor简介 SharedPreferences保存的数据主要是类似于配置信息格式的数据,因此其保存的数据主要是简单的类型的ke ...

  9. Android实现数据存储技术

    转载:Android实现数据存储技术 本文介绍Android中的5种数据存储方式. 数据存储在开发中是使用最频繁的,在这里主要介绍Android平台中实现数据存储的5种方式,分别是: 1 使用Shar ...

随机推荐

  1. Java算法-hash算法

    Hash ,一般翻译做“ 散列” ,也有直接音译为“ 哈希” 的,就是把任意长度的输入(又叫做预映射, pre-image ),通过散列算法,变换成固定长度的输出,该输出就是散列值.这种转换是一种压缩 ...

  2. [Angularjs]ng-class,ng-class-even,ng-class-odd

    写在前面 最近在通过angularjs将数据绑定到前端,其中也涉及到很多新的东西,一些效果还是很有必要实现的.在使用中发现ng-class,ng-class-even.ng-class-odd的使用, ...

  3. spark-submit提示资源不足

    ensure that workers are registered and have sufficient resources spark-cluster启动的配置里配置了每个worker的内存,如 ...

  4. Linux 下模拟Http 的get or post请求(curl和wget两种方法)

    一.get请求: 1.使用curl命令: curl "http://www.baidu.com"  如果这里的URL指向的是一个文件或者一幅图都可以直接下载到本地curl -i & ...

  5. 严格遵守“第一级DOM”能够让你避免与兼容性有关的任何问题

    1级DOM:1级DOM在1998年10月份成为W3C的提议,由DOM核心与DOM HTML两个模块组成.DOM核心能映射以XML为基础的文档结构,允许获取和操作文档的任意部分.DOM HTML通过添加 ...

  6. xcrun: error: active developer path ("/Volumes/Xcode/Xcode-beta.app/Contents/Developer") does not exist, use `xcode-select --swi

    xcrun: error: active developer path ("/Volumes/Xcode/Xcode-beta.app/Contents/Developer") d ...

  7. Yii2事件

    namespace app\components; use yii\base\Component; use yii\base\Event; class MessageEvent extends Eve ...

  8. LinkedList和ArrayList的区别/何时使用LinkedList和ArrayList

    1.ArrayList是实现了基于动态数组的数据结构,LinkedList基于链表的数据结构. 2.对于随机访问get和set,ArrayList觉得优于LinkedList,因为LinkedList ...

  9. visual studio 2010 破解版 破解方法

    1.Microsoft Visual Studio 2010下载(均来自微软官网) 高级版(Premium) [建议下载]       http://download.microsoft.com/do ...

  10. 在Microsoft-IIS/10.0上面部署mvc站点的时候,出现404的错误

    写在前面 在家自己弄了一个项目,想部署在电脑上用手机来访问,总是出现404的错误.路由什么的没有写错啊,最后发现是映射程序的问题,在安装的时候iis很多功能没有安装,又将iis的其他没有安装的功能勾选 ...