除了SQLite数据库外,SharedPreferences也是一种轻型的数据存储方式,它的本质是基于XML文件存储key-value键值 对数据,通常用来存储一些简单的配置信息。其存储位置在/data/data/<包名>/shared_prefs目录下。 SharedPreferences对象本身只能获取数据而不支持存储和修改,存储修改是通过Editor对象实现。实现 SharedPreferences存储的步骤如下:

  一、根据Context获取SharedPreferences对象

  二、利用edit()方法获取Editor对象。

  三、通过Editor对象存储key-value键值对数据。

  四、通过commit()方法提交数据。

  具体实现代码如下:

 1 package com.example.sharedpreference;
 2 import android.annotation.SuppressLint;
 3 import android.app.Activity;
 4 import android.content.SharedPreferences;
 5 import android.os.Bundle;
 6 import android.util.Log;
 7 import android.view.View;
 8 import android.widget.Button;
 9 import android.widget.EditText;
10 import android.widget.TextView;
11 import android.widget.Toast;
12 import com.example.lesson14.R;
13
14 @SuppressLint("WorldWriteableFiles")
15 public class SharedPreferencesActivity extends Activity {
16     private EditText nameEditText;
17     private EditText ageEditText;
18     private Button saveBtn;
19     private Button showBtn;
20     private TextView resultText;
21     @Override
22     public void onCreate(Bundle savedInstanceState) {
23         super.onCreate(savedInstanceState);
24         setContentView(R.layout.preference_layout);
25         nameEditText = (EditText)this.findViewById(R.id.name);
26         ageEditText = (EditText)this.findViewById(R.id.age);
27         resultText = (TextView)this.findViewById(R.id.showText);
28         saveBtn = (Button)this.findViewById(R.id.saveButton);
29         showBtn = (Button)this.findViewById(R.id.showButton);
30         saveBtn.setOnClickListener(listener);
31         showBtn.setOnClickListener(listener);
32 //        read a SharedPreferences
33 //      SharedPreferences mSP = getSharedPreferences("SP", MODE_PRIVATE);
34 //        String name = mSP.getString("NAME", "");
35 //        String age = mSP.getString("Age", "");
36 //        nameEditText.setText(name);
37 //        ageEditText.setText(age);
38
39     }
40
41     private View.OnClickListener listener = new View.OnClickListener(){
42         public void onClick(View v) {
43             Button button = (Button)v;
44             switch (button.getId()) {
45             case R.id.saveButton:
46                 SaveData();
47                 Toast.makeText(SharedPreferencesActivity.this, "保存成功", Toast.LENGTH_LONG).show();
48                 break;
49             case R.id.showButton:
50                 ShowData();
51                 break;
52             }
53         }
54     };
55     public void SaveData(){
56         String nameString = nameEditText.getText().toString();
57         int ageInt = Integer.parseInt(ageEditText.getText().toString());
58         if (nameString.equals("")|| ageInt == 0) {
59             Toast.makeText(getApplicationContext(), "username or age is null or uncrect,please input again", Toast.LENGTH_LONG).show();
60         }    else{
61             // get name,age
62                 SharedPreferences mSharedPreferences = getSharedPreferences("SP", MODE_PRIVATE);
63                 SharedPreferences.Editor editor = mSharedPreferences.edit();
64                 editor.putString("NAME", nameString);
65                 editor.putInt("Age", ageInt);
66                 editor.apply();
67                 Log.i("Tag", "name: "+nameString +" pwd:"+ageInt);
68     }
69 }
70     public void ShowData() {
71         SharedPreferences mSharedPreferences = getSharedPreferences("SP", MODE_PRIVATE);
72         String name = mSharedPreferences.getString("NAME", "");
73         int age =mSharedPreferences.getInt("Age",1 );
74         resultText.setText("姓名:" + name + ",年龄:" + age);
75     }
76 }

这段代码执行过后,即在/data/data/com.test/shared_prefs目录下生成了一个SP.xml文件,一个应用可以创建多个这样的xml文件。图就不贴了

下面是它的布局

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:orientation="vertical"
 4     android:layout_width="fill_parent"
 5     android:layout_height="fill_parent">
 6     <RelativeLayout
 7         android:layout_width="wrap_content"
 8         android:layout_height="wrap_content">
 9         <TextView android:layout_width="wrap_content"
10             android:layout_height="wrap_content"
11             android:text="@string/name"
12             android:textSize="20px"
13             android:id="@+id/nameLable" />
14         <EditText android:layout_width="fill_parent"
15             android:layout_height="wrap_content"
16             android:layout_toRightOf="@id/nameLable"
17             android:layout_alignTop="@id/nameLable"
18             android:layout_marginLeft="10px"
19             android:id="@+id/name" />
20     </RelativeLayout>
21     <RelativeLayout
22         android:layout_width="wrap_content"
23         android:layout_height="wrap_content">
24         <TextView android:layout_width="wrap_content"
25             android:layout_height="wrap_content"
26             android:textSize="20px"
27             android:text="@string/age"
28             android:id="@+id/ageLable" />
29         <EditText android:layout_width="fill_parent"
30             android:layout_height="wrap_content"
31             android:layout_toRightOf="@id/ageLable"
32             android:layout_alignTop="@id/ageLable"
33             android:layout_marginLeft="10px"
34             android:id="@+id/age"
35             android:numeric="integer"/>
36     </RelativeLayout>
37     <RelativeLayout
38
39         android:layout_width="wrap_content"
40         android:layout_height="wrap_content">
41         <Button android:layout_width="wrap_content"
42             android:layout_height="wrap_content"
43             android:text="@string/button"
44             android:id="@+id/saveButton" />
45         <Button android:layout_width="wrap_content"
46             android:layout_height="wrap_content"
47             android:text="@string/showButton"
48             android:layout_toRightOf="@id/saveButton"
49             android:layout_alignTop="@id/saveButton"
50             android:id="@+id/showButton" />
51     </RelativeLayout>
52     <TextView android:layout_width="fill_parent"
53             android:layout_height="wrap_content"
54             android:textSize="20px"
55             android:id="@+id/showText" />
56 </LinearLayout>

View Code

SharedPreferences对象与SQLite数据库相比,免去了创建数据库,创建表,写SQL语句等诸多操作,相对而言更加方便,简洁。但是 SharedPreferences也有其自身缺陷,比如其职能存储boolean,int,float,long和String五种简单的数据类型,比 如其无法进行条件查询等。所以不论SharedPreferences的数据存储操作是如何简单,它也只能是存储方式的一种补充,而无法完全替代如 SQLite数据库这样的其他数据存储方式。

在上面的提交的步骤用到了两种方法:editor.commit();editor.apply();

注意:这两个方法的区别在于:

1. apply没有返回值而commit返回boolean表明修改是否提交成功

2. apply是将修改数据原子提交到内存, 而后异步真正提交到硬件磁盘, 而commit是同步的提交到硬件磁盘,因此,在多个并发的提交commit的时候,他们会等待正在处理的commit保存到磁盘后在操作,从而降低了效率。而apply只是原子的提交到内容,后面有调用apply的函数的将会直接覆盖前面的内存数据,这样从一定程度上提高了很多效率。

转载于:https://www.cnblogs.com/lyc602/p/3867375.html

Android数据的四种存储方式SharedPreferences、SQLite、Content Provider和File 之 —— SharedPreferences...相关推荐

  1. Android数据的四种存储方式SharedPreferences、SQLite、Content Provider和File (四) —— ContentProvider...

    ContentProvider是安卓平台中,在不同应用程序之间实现数据共享的一种机制.一个应用程序如果需要让别的程序可以操作自己的数据,即可采用这种机制.并且此种方式忽略了底层的数据存储实现,Cont ...

  2. Android数据的四种存储方式

    很清晰的思路,转自Android数据的四种存储方式 作为一个完成的应用程序,数据存储操作是必不可少的.因此,Android系统一共提供了四种数据存储方式.分别是:SharePreference.SQL ...

  3. [转][Android]Android数据的四种存储方式

    android.database.sqlite 类 SQLiteQueryBuilder java.lang.Object android.database.sqlite.SQLiteQueryBui ...

  4. [置顶] Android数据的四种存储方式SharedPreferences、SQLite、Content Provider和File (二) —— SQLite...

    SQLite是一种转为嵌入式设备设计的轻型数据库,其只有五种数据类型,分别是: NULL: 空值 INTEGER: 整数 REAL: 浮点数 TEXT: 字符串 BLOB: 大数据 在SQLite中, ...

  5. Android数据的四种存储方式SharedPreferences、SQLite、Content Provider和File (二) —— SQLite...

    SQLite是一种转为嵌入式设备设计的轻型数据库,其只有五种数据类型,分别是: NULL: 空值 INTEGER: 整数 REAL: 浮点数 TEXT: 字符串 BLOB: 大数据 在SQLite中, ...

  6. android数据的五种存储方式

    Android提供了5种方式存储数据 1 使用SharedPreferences存储数据 它的本质是基于XML文件存储key-value键值对数据,通常用来存储一些简单的配置信息. 其存储位置在/da ...

  7. 数据存储-大数据的三种存储方式

    互联网时代各种存储框架层出不穷,眼花缭乱,比如传统的关系型数据库:Oracle.MySQL:新兴的NoSQL:HBase.Cassandra.Redis:全文检索框架:ES.Solr等.如何为自己的业 ...

  8. Hive的四种存储方式Stored as ?

  9. 数据存储四种常见方式

    常见的数据存储方式有四种:在线存储.近线存储.脱机存储和站外保护. 不同的存储方式提供不同的获取便利性.安全性和成本开销等级. 在大多数场景中,四种存储方式被混合使用以达到最有效的存储策略. 来看一看 ...

最新文章

  1. Gut:刘星吟/王益超/曹爱华等揭示孤独症患儿肠道菌群发育轨迹图谱(赵方庆点评)...
  2. python脚本调度程序_Windows 任务调度程序定时执行Python脚本
  3. Gartner:大数据投资增长,但计划投资的组织机构却在减少
  4. java导出pdf集合_java实现导出pdf-Go语言中文社区
  5. 生物大数据时代,如何做好数据管理和再利用,发IF10+的数据库文章?
  6. 不容错过!我的Mac装机软件清单,Mac新手看过来!
  7. python装饰器哪个好用变女生_Python女神分享教程之Python 装饰器
  8. 编写一个Rubygem, 如何在gem 被Install之前运行一段程序?
  9. auto static 的区别
  10. 小米MIX 4真机亮屏谍照曝光:四边框极窄,震撼
  11. Android自定义控件(四)——让每一个Activity UI都具有弹性
  12. 【数据结构】堆的手动模拟实现
  13. 日志报错:kernel: blk_update_request: I/O error, dev fd0, sector 0
  14. 参数化建模类毕业论文文献有哪些?
  15. SecoClient在win10系统中连接失败解决方案
  16. android bugreport 解析
  17. 创新实训1 小组分工以及项目部署
  18. 35搜索插入位置之Leecode—《数组篇》(二分法)
  19. Python - 文件基础操作
  20. 单相桥式整流电容滤波及稳态时的波形分析

热门文章

  1. 细说嵌入式Linux文件系统的制作方法
  2. PMP项目管理认证体系
  3. 检讨:丢了我女儿和项目设计感想
  4. 蓝桥杯 ALGO-23 算法训练 一元三次方程求解
  5. 非常详细的 Docker 学习笔记
  6. Android进阶: 10分钟实现NDK-JNI 开发教程
  7. Shiro-从数据表中初始化资源和权限
  8. 使用oracle数据库和MySQL数据库时hibernate的映射文件.hbm.xml的不同
  9. C、C++用指针引用的差异
  10. iis 在站点中新建虚拟目录站点之后,虚拟目录中的 web.config 与 主站点中的 web.config冲突解决方案...