Android通过记住密码功能学习数据存储类SharedPreferences详解及实例
作者:ForrestWoo 发布时间:2023-05-21 21:37:49
SharedPreferences是Android中存储简单数据的一个工具类。可以想象它是一个小小的Cookie,它通过用键值对的方式把简单数据类型(boolean、int、float、long和String)存储在应用程序的私有目录下(data/data/包名/shared_prefs/)自己定义的xml文件中。
一、简介
它提供一种轻量级的数据存储方式,通过eidt()方法来修改里面的内容,通过Commit()方法来提交修改后的内容。
二、重要方法
public abstract boolean contains (String key) :检查是否已存在该文件,其中key是xml的文件名。
edit():为preferences创建一个编辑器Editor,通过创建的Editor可以修改preferences里面的数据,但必须执行commit()方法。
getAll():返回preferences里面的多有数据。
getBoolean(String key, boolean defValue):获取Boolean型数据
getFloat(String key, float defValue):获取Float型数据
getInt(String key, int defValue):获取Int型数据
getLong(String key, long defValue):获取Long型数据
getString(String key, String defValue):获取String型数据
registerOnSharedPreferenceChangeListener(SharedPreferences.OnSharedPreferenceChangeListener listener):注册一个当preference发生改变时被调用的回调函数。
unregisterOnSharedPreferenceChangeListener(SharedPreferences.OnSharedPreferenceChangeListener listener):删除当前回调函数。
三、重要接口SharedPreferences.Editor
1.简介
用于修改SharedPreferences对象的内容,所有更改都是在编辑器所做的批处理,而不是复制回原来的SharedPreferences或持久化存储,直到你调用commit(),才将持久化存储。
2.重要方法
clear():清除内容。
commit():提交修改
remove(String key):删除preference
下面通过“记住密码”功能
四、实例
效果图如下
首页
登录成功后的页面
当第一次登录点击”记住密码“后,第二次打开时的页面
2.代码
布局文件 login.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:gravity="right" android:layout_gravity="right"
android:background="@drawable/default_bg" android:orientation="vertical">
<TableLayout android:layout_width="fill_parent"
android:layout_height="wrap_content" android:stretchColumns="1">
<TableRow android:gravity="center" android:layout_gravity="center">
<ImageView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:id="@+id/ivlogo"
>
</ImageView>
</TableRow>
</TableLayout>
<TableLayout android:layout_width="fill_parent"
android:layout_height="wrap_content" android:stretchColumns="1">
<TableRow android:layout_marginTop="100dip">
<TextView android:layout_width="wrap_content"
android:layout_marginLeft="20dip" android:gravity="center_vertical"
android:layout_height="wrap_content" android:id="@+id/tvaccount"
android:text="帐号:" android:textSize="20sp">
</TextView>
<EditText android:layout_width="70px" android:layout_height="wrap_content"
android:id="@+id/etaccount" android:layout_marginRight="20dip"
android:maxLength="20"></EditText>
</TableRow>
<TableRow android:layout_marginTop="10dip">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/tvpw"
android:layout_marginLeft="20dip" android:gravity="center_vertical"
android:text="密码:" android:textSize="20sp">
</TextView>
<EditText android:layout_width="70px" android:layout_height="wrap_content"
android:layout_marginRight="20dip" android:id="@+id/etpw"
android:inputType="textPassword"></EditText>
</TableRow>
</TableLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:orientation="horizontal" android:layout_marginTop="5dip" android:layout_marginRight="20dip">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/tvclear"
android:text="清除Cookies" android:textColor="#aa0000" android:textSize="12px"></TextView>
</LinearLayout>
<TableLayout android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_marginTop="20dip">
<TableRow android:gravity="center" android:layout_width="fill_parent">
<Button android:layout_width="100px" android:layout_height="wrap_content"
android:id="@+id/btnlogin" android:layout_gravity="center"
android:text="登录"></Button>
<Button android:layout_width="100px" android:layout_height="wrap_content"
android:id="@+id/btnexit" android:layout_gravity="center"
android:text="退出"></Button>
</TableRow>
</TableLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:orientation="horizontal" android:layout_marginTop="25dip">
<CheckBox android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/cbrp"
android:text="记住密码" android:textSize="12px"></CheckBox>
<CheckBox android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/cbal"
android:text="自动登录" android:textSize="12px"></CheckBox>
</LinearLayout>
</LinearLayout>
java代码
package com.wjq;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.wjq.beans.User;
import com.wjq.func.UserMgr;
public class Login extends Activity {
private EditText etAccount;
private EditText etPW;
private Button btnLogin;
private Button btnExit;
private CheckBox cbrp;
private CheckBox cbal;
private UserMgr userMgr;
private User user;
private SharedPreferences sp;
private TextView tvClear;
/*
* (non-Javadoc)
*
* @see android.app.Activity#onCreate(android.os.Bundle)
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
etAccount = (EditText) findViewById(R.id.etaccount);
etPW = (EditText) findViewById(R.id.etpw);
cbrp = (CheckBox) findViewById(R.id.cbrp);
cbal = (CheckBox) findViewById(R.id.cbal);
btnLogin = (Button) findViewById(R.id.btnlogin);
btnExit = (Button) findViewById(R.id.btnexit);
tvClear=(TextView)findViewById(R.id.tvclear);
InitConfig();
cbrp
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
sp = getSharedPreferences("UserInfo", 0);
sp.edit().putBoolean("cbrp", isChecked).commit();
}
});
cbal
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
sp = getSharedPreferences("UserInfo", 0);
sp.edit().putBoolean("cbal", isChecked).commit();
}
});
btnLogin.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
user = new User(etAccount.getText().toString(), etPW.getText()
.toString());
Log.i("tag", "Account:" + etAccount.getText().toString());
Log.i("tag", "Password:" + etPW.getText().toString());
userMgr = new UserMgr();
Boolean flag = userMgr.CheckUser(user, Login.this);
if (!flag) {
Toast.makeText(Login.this, "用户验证错误!", 1000).show();
}
else {
if (cbrp.isChecked()) {
sp = getSharedPreferences("UserInfo",
Context.MODE_WORLD_WRITEABLE
| Context.MODE_WORLD_READABLE);
sp.edit().putString("account",
etAccount.getText().toString()).commit();
sp.edit().putString("password",
etPW.getText().toString()).commit();
}
}
}
});
btnExit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
System.exit(0);
}
});
tvClear.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {sp=getSharedPreferences("UserInfo", 0);
sp.edit().clear().commit();
}});
}
//初始化配置
private void InitConfig() {
sp = getSharedPreferences("UserInfo", 0);
etAccount.setText(sp.getString("account", null));
etPW.setText(sp.getString("password", null));
cbal.setChecked(sp.getBoolean("cbal", false));
cbrp.setChecked(sp.getBoolean("cbrp", false));
}
}
说明:
1.写内容
sp = getSharedPreferences("UserInfo", 0);
sp.edit().putBoolean("cbal", isChecked).commit();
UserInfo是指xml文件的文件名,如果此文件已存在则直接向其中写内容“isChecked”的值,首先通过SharedPreferences的edit()方法创建editor,然后调用commit()方法提修改
2.读内容
sp = getSharedPreferences("UserInfo", 0);
etAccount.setText(sp.getString("account", null));
etPW.setText(sp.getString("password", null));
cbal.setChecked(sp.getBoolean("cbal", false));
cbrp.setChecked(sp.getBoolean("cbrp", false));


猜你喜欢
- 归并排序算法思想:分而治之(divide - conquer);每个递归过程涉及三个步骤第一, 分解: 把待排序的 n 个元素的序列分解成两
- 前言以前我们还需要手写数据库设计文档、现在可以通过引入screw核心包来实现Java 数据库文档一键生成。话不多说、直接上代码演示。支持的数
- 在笔试编程过程中,关于数据的读取如果迷迷糊糊,那后来的编程即使想法很对,实现很好,也是徒劳,于是在这里认真总结了Java Scanner 类
- 所谓c#的委托就是说把函数当参数来传递。这个在js完全就用不着搞什么委托东西,直接转就是了。而对于C#来说则不是这样!一个函数,如果它的参数
- .NET开发人员首选的方法,通过COM组件调用Office软件本身来实现文件的创建和读写,但是数据量较大的时候异常缓慢;如下代码所示已经做了
- 零、业务逻辑Controller-->service接口-->serviceImpl-->dao接口-->daoIm
- 一、需求对于Java开发工程师来说,可能手头上同时负责不同的项目,但是由于历史的原因,Java版本可能没有做到统一升级,有的项目是使用JDK
- 以下是介绍利用List的subList方法实现对List分页,废话不多说了,直接看代码把/** *//** * List分页 &
- 调用SAP WebService服务需要转换操作1、通过浏览器访问SAP WebService地址,进行验证并生成wsdl文件地址并不是可以
- 1、什么是 生命周期?Maven 强大的原因是有一个十分完善的生命周期,生命周期可以理解为项目构建步骤的集合,它定义了各个构建环节的执行顺序
- 有时候需要根据条件查询得出的数据较多,需要分页显示到页面上。这时点击下一页就不方便每次带查询条件在数据库中分页。可以在list中进行分页。p
- 前言平时我们都有用到LeakCanary来分析内存泄露的情况,这里可以来看看LeakCanary是如何实现的,它的内部又有哪些比较有意思的操
- 这篇文章主要介绍了spring boot 2整合swagger-ui过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的
- 学会了Paint,Canvas的基本用法之后,我们就可以动手开始实践了,先写个简单的图片加载进度条看看。按照惯例,先看效果图,再决定要不要往
- 声明类定义类:class MyClass { // 字段、构造函数和 // 方法声明}
- 本次和大家分享的是怎么来消费服务,上篇文章讲了使用Feign来消费,本篇来使用rest+ribbon消费服务,并且通过轮询方式来自定义了个简
- 数据加解密的实现方式多种多样,在mybatis环境中数据加解密变得非常简单易用,本文旨在提供参考,在生产中应尽可能完成单元测试,开展足够的覆
- Spring容器可以在不使用<constructor-arg>和<property>元素的情况下自动装配相互协作的b
- 序言:使用MyBatis3提供的注解可以逐步取代XML,例如使用@Select注解直接编写SQL完成数据查询,使用@SelectProvid
- 前言在我们日常的开发过程中通过打印详细的日志信息能够帮助我们很好地去发现开发过程中可能出现的Bug,特别是在开发Controller层的接口