SharedPreferences是Android中一种轻型的数据存储类。本质上是基于XML文件进行存储Key-Value键值对的数据,生成的XML文件的目录在/data/data/包名/Shared_Pref/下。主要是用来存储一些简单的配置信息,如登录时是否保存用户名密码等。

SharedPreferences本身只能获取数据而不支持存储或修改,存储修改是通过SharedPreferences的一个内部接口Editor来实现的。

实现SharedPreferences存储的步骤如下:

① 获取SharedPreferences对象;

② 获取SharedPreferences.Editor对象;

③ 通过Editor接口的putXxx方法保存K-V键值对。Xxx表示不同的数据类型(float,int,String,boolean,long);

④ 使用Editor接口的commit方法进行操作的提交。

使用SharedPreferences的过程比较简单,下面通过一个保存用户名的小案例演示一下SharedPreferences的简单使用。

主布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:orientation="horizontal"
android:layout_marginTop="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/tvUsername"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="14dp"
android:text="用户名"
android:textSize="20dp"
android:textAlignment="center"/>
<EditText
android:id="@+id/etUsername"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/Base.V7.Widget.AppCompat.EditText"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp">
<TextView
android:id="@+id/tvPassword"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="14dp"
android:text="密 码"
android:textSize="20dp"
android:textAlignment="center"/>
<EditText
android:id="@+id/etPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:theme="@style/Base.V7.Widget.AppCompat.EditText"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp">
<TextView
android:id="@+id/tvRememberUsername"
android:text="保存用户名"
android:textSize="15dp"
android:layout_marginLeft="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<CheckBox
android:id="@+id/cbRememberUsername"
android:layout_width="wrap_content"
android:layout_height="wrap_content" /> </LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp">
<Button
android:id="@+id/btnLogin"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_marginRight="15dp"
android:layout_marginLeft="10dp"
android:layout_height="60dp"
android:text="登录"
android:textSize="20dp"/> <Button
android:id="@+id/btnCancel"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_marginRight="10dp"
android:layout_marginLeft="5dp"
android:layout_height="60dp"
android:text="取消"
android:textSize="20dp"/> </LinearLayout>
</LinearLayout>

activity_main

MainActivity.java

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
//声明控件
private EditText etUsername, etPassword;
private TextView tvUsername, tvPassword, tvSaveUsername;
private CheckBox cbSaveUsername;
private Button btLogin, btCancel;
//声明SharedPreferences对象
private SharedPreferences preferences;
//声明Editor对象
private SharedPreferences.Editor editor; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();//初始化控件
/**
* 通过getSharedPreferences方法获取SharedPreferences对象,
* getSharedPreferences(String name,int mode)
* name: 生成的XML文件的名字
* mode: 生成的XML文件的权限(是否能被其他程序读取等)
*
* 也可以使用PreferenceManager.getDefaultSharedPreferences(this)获取SharedPreferences对象,
* 这样生成的XML文件名为: 包名+“_preferences”
* XML权限为:MODE_PRIVATE
*/
// preferences = PreferenceManager.getDefaultSharedPreferences(this);
preferences = getSharedPreferences("myPref", MODE_PRIVATE);
//获取Editor对象
editor = preferences.edit();
//通过SharedPreferences对象的getXxx方法获取Key对应的Value,第二个参数为默认值
String name = preferences.getString("username", "");
//如果name为空,说明还未进行过用户名的存储
if (name == null) {
cbSaveUsername.setChecked(false);
} else {//如果不为空则将已存储的用户名自动填写到编辑框中
cbSaveUsername.setChecked(true);
etUsername.setText(name);
} } //初始化控件
private void initViews() {
etUsername = (EditText) findViewById(R.id.etUsername);
etPassword = (EditText) findViewById(R.id.etPassword);
tvUsername = (TextView) findViewById(R.id.tvUsername);
tvPassword = (TextView) findViewById(R.id.tvPassword);
tvSaveUsername = (TextView) findViewById(R.id.tvRememberUsername);
cbSaveUsername = (CheckBox) findViewById(R.id.cbRememberUsername);
btLogin = (Button) findViewById(R.id.btnLogin);
btCancel = (Button) findViewById(R.id.btnCancel);
btLogin.setOnClickListener(this);
btCancel.setOnClickListener(this);
} //按钮点击事件
@Override
public void onClick(View v) {
//获取到编辑框中的用户名和密码
String name = etUsername.getText().toString();
String pass = etPassword.getText().toString(); switch (v.getId()) {
//登录按钮的点击处理
case R.id.btnLogin:
//如果用户名和密码合法
if ("admin".equals(name) && "abc123".equals(pass)) {
//如果勾选了保存用户名的复选框,则将用户名存储到XML文件中
if (cbSaveUsername.isChecked()) {
editor.putString("username", name);
} else {//如果没有勾选则将用户名从XML文件中移除(如果有的话)
editor.remove("username");
}
//使用Editor对象操作后,需要调用commit方法进行提交,不然所有的操作都无效。类似与数据库中事务的提交
editor.commit();
Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "登录失败", Toast.LENGTH_SHORT).show();
}
break;
case R.id.btnCancel:
break;
}
}
}

完整源码 :  点击下载

作者:caobotao
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。

Android数据存储之SharedPreferences使用的更多相关文章

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

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

  2. Android数据存储方式--SharedPreferences

    Android数据存储方式有如下四种:SharedPreferences.存储到文件.SQLite数据库.内容提供者(Content provider).存储到网络服务器. 本文主要介绍一下Share ...

  3. Android 数据存储之 SharedPreferences储存

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

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

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

  5. Android数据存储之SharedPreferences存储

    安卓系统为应用提供了系统级的配置存储方案,它就是靠SharedPreferences接口来实现的,该接口存储的所有信息都是以名值对的形式保存,但其保存的数据类型也仅限于基本数据类型,如字符串.整形.布 ...

  6. android数据存储之SharedPreferences

    一.SharedPreferences简介      (1)SharedPreferences是Android平台上一个轻量级的存储类,用来保存应用的一些常用配置,比如Activity状态,Activ ...

  7. Android数据存储之SharedPreferences及如何安全存储

    前言: 最近一直在学习ios的数据存储,当学习到NSUserDefaults的时候让我回想起了SharedPreferences,今天闲来无事,想着总结一下SharedPreferences的使用. ...

  8. Android数据存储之sharedpreferences与Content Provider

    android中对数据操作包含有: file, sqlite3, Preferences, ContectResolver与ContentProvider前三种数据操作方式都只是针对本应用内数据,程序 ...

  9. Android数据存储:Shared Preferences

    Android数据存储之SharedPreferences 在Android系统中提供了多种存储技术.通过这些存储技术可以将数据存储在各种存储介质上, Android 为数据存储提供了如下几种方式:1 ...

随机推荐

  1. JavaScript学习-2循环

    文章目录 ----------①console函数 ----------②for循环 ----------③跳出循环 ----------④练习题:口诀表 ----------⑤练习题:幼兔 ---- ...

  2. intellij ideal 在erlang 开发环境遇到的一些小问题

    由于之前重装电脑,公司电脑上的erlang开发环境重新搭建了,但是由于导入项目错误,直接将项目删掉重新又导入了一次,但是发现使用的sdk在联想输入方面出现了问题,写个东西记一下自己犯的错误. 修正方法 ...

  3. 项目(三)PXE高效能批量网络装机

    PXE:预启动执行环境 PXE是由intel公司开发的网络引导技术,工作在Client/Server模式,允许客户机通过网络从远程服务器下载引导镜像,并加载安装文件或者整个操作系统. 若要搭建PXE网 ...

  4. mysql 判断字符串是否有某个字符

    代码: SELECT LOCATE("_","a_123") -->2  (返回字符的位置,从1开始) SELECT ('123' REGEXP '[^0 ...

  5. [leetcode]86. Partition List划分链表

    Given a linked list and a value x, partition it such that all nodes less than x come before nodes gr ...

  6. [leetcode]32. Longest Valid Parentheses最长合法括号子串

    Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...

  7. pycharm快捷键及中文说明【使用翻译工具一条一条翻译】

    Search Everywhere: Double Shift Go to File : Ctrl+Shilf+N Recent Files: Ctrl+E Navigation Bar: Alt+H ...

  8. python 常用标准库

    标准库和第三方库第一手资料: 在线: 官方文档(https://docs.python.org/) 离线:交互式解释器(dir().help()函数),IPython(tab键提示.?.??) 一.  ...

  9. 洛谷1345 [USACO5.4]奶牛的电信Telecowmunication

    原题链接 最小割点数转换成最小割边数的模板题(不过这数据好小). 每个点拆成两个点,连一条容量为\(1\)的边,原图的边容量定为\(+\infty\),然后跑最大流即可. 这里用的是\(Dinic\) ...

  10. 图片利用 new Image()预加载原理 和懒加载的实现原理

    二:预加载和懒加载的区别 预加载与懒加载,我们经常经常用到,这些技术不仅仅限于图片加载,我们今天讨论的是图片加载: 图片预加载:顾名思义,图片预加载就是在网页全部加载之前,提前加载图片.当用户需要查看 ...