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 关键字 native

    native 关键字说明其修饰的方法是一个原生态方法,方法对应的实现不是在当前文件中,而是在用其他语言实现的文件中.Java语言本身不能对操作系统底层进行访问和操作,但是可以通过JNI接口调用其他语言 ...

  2. 可视化HTML编辑器

    [荐] 可视化HTML编辑器 CKEditor CKEditor是新一代的FCKeditor,是一个重新开发的版本.CKEditor是全球最优秀的网页在线文字编辑器之一,因其惊人的性能与可扩展性而广泛 ...

  3. 【HDU 1757】 A Simple Math Problem

    题 Description Lele now is thinking about a simple function f(x). If x < 10 f(x) = x. If x >= 1 ...

  4. iOS-编译简单静态库初探

    首先声明,我写的这些网上都有更详细的内容,在这里只是写下我自己总结的一些重要内容,具体步骤如下: 事先准备:新建工程-Framework & Library - Cocoa Touch Sta ...

  5. Day4_计算器

    read me 1.构造三个函数,乘除(mad),加减(aas),去括号(par): 2.获取表达式字符串之后,判断是否包含“+-*/()”等字符,包含则下一步3:不包含,返回字符串: 3.par 函 ...

  6. h5页面,改变数字默认颜色

    最近遇到一个非常变态的bug,有一串数字,我设置color为白色,在pc端浏览器,无变化,但是到了手机端,会由白色跳成黑色,我无解啊... 刚刚找到方法,如下: <meta name=" ...

  7. Uva11300 Spreading the Wealth

    设第i个人需要给第i+1个人的金币数为xi(xi为负代表收到钱),列出一大堆方程. 设第i个人给第i-1个人的钱为xi(xi<0表示第i-1个人给第i个人钱).计算出最后每个人应该有的钱m,解方 ...

  8. Process manufacturing和Discrete manufacturing的区别

    Process manufacturing(Process industry) 加工制造,或者加工工业.其一个重要特征是,原材料被加工成成品后,我们再也无法将它恢复成原料,比如,苹果罐头,我们再没法把 ...

  9. C#通过编程方式实现Ping

    代码是照着书敲的,贴出来方便平时参考 using System; using System.Collections.Generic; using System.Linq; using System.T ...

  10. JAVA的面向对象编程--------课堂笔记

    面向对象主要针对面向过程. 面向过程的基本单元是函数.   什么是对象:EVERYTHING IS OBJECT(万物皆对象)   所有的事物都有两个方面: 有什么(属性):用来描述对象. 能够做什么 ...