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. 【BZOJ 2002】【Hnoi 2010】弹飞绵羊 分块||Link Cut Tree 两种方法

    ShallWe,Yveh,hmy,DaD3zZ,四人吃冰糕从SLYZ超市出来后在马路上一字排开,,,吃完后发现冰糕棍上写着:“向狮子座表白:愿做你的小绵羊”,,, 好吧在这道题里我们要弹飞绵羊,有分块 ...

  2. Java-优化技术

    常用的: 1.优化循环.通过重新组织重复的子表达式来提高循环体的运行性能. 2减少使用对象的数量来提高运行性能. 3.缩减网络传输数据来缩短等待时间. 其他: 1.采用对象池技术,提高对象的利用效率. ...

  3. 【CodeForces 227A】Where do I Turn?叉积

    题意 ABC的位置关系只有三种可能: 1.在一条直线上,输出TOWARDS A--B--C 2.AB 和BC垂直,B为直角顶点,AB左侧是C,输出LEFT C--B | A 3.AB 和BC垂直,B为 ...

  4. Cocos2d-X3.0 刨根问底(五)----- Node类及显示对象列表源码分析

    上一章 我们分析了Cocos2d-x的内存管理,主要解剖了 Ref.PoolManager.AutoreleasePool这三个类,了解了对象是如何自动释放的机制.之前有一个类 Node经常出现在各种 ...

  5. 14.Android之Layout布局学习

    Android布局主要有5种,接下来学习总结下. 1) 最常见的线性布局 LinearLayout 线性布局是Android布局中最简单的布局,也是最常用,最实用的布局. android:orient ...

  6. POJ1201 Intervals

    Description You are given n closed, integer intervals [ai, bi] and n integers c1, ..., cn. Write a p ...

  7. ARP协议格式、ARP运行机制入门学习

    相关学习资料 http://baike.baidu.com/view/149421.htm?fromtitle=ARP%E5%8D%8F%E8%AE%AE&fromid=1742212& ...

  8. POJ 2752 Seek the Name, Seek the Fame

    传送门 Time Limit: 2000MS   Memory Limit: 65536K Total Submissions: 14761   Accepted: 7407 Description ...

  9. IOS基础之 (七) 分类Category

    一 Category 分类:Category(类目,类别) (OC有) 命名:原来的类+类别名(原来的类名自动生成,只要写后面的类别名,一般以模块名为名.比如原来类 Person,新建分类 Ct,新建 ...

  10. Nutch的配置以及动态网站的抓取

    http://blog.csdn.net/jimanyu/article/details/5619949 一:配置Nutch: 1.解压缩的nutch后,以抓取http://www.163.com/为 ...