SharedPreferences是Android中存储简单数据的一个工具类。可以想象它是一个小小的Cookie,它通过用键值对的方式把简单 数据类型(boolean、int、float、long和String)存储在应用程序的私有目录下(data/data/包名 /shared_prefs/)自己定义的xml文件中。

重要方法

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.重要方法

lear():清除内容。

commit():提交修改

remove(String key):删除preference

效果图

代码

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="">
<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="">
<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=""></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", );
sp.edit().putBoolean("cbrp", isChecked).commit();
} }); cbal
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
sp = getSharedPreferences("UserInfo", );
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, "用户验证错误!", ).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();
}
}); tvClear.setOnClickListener(new OnClickListener(){ @Override
public void onClick(View v) {sp=getSharedPreferences("UserInfo", ); sp.edit().clear().commit();
}});
}
//初始化配置
private void InitConfig() {
sp = getSharedPreferences("UserInfo", );
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", );
sp.edit().putBoolean("cbal", isChecked).commit();
UserInfo是指xml文件的文件名,如果此文件已存在则直接向其中写内容“isChecked”的值,首先通过SharedPreferences的edit()方法创建editor,然后调用commit()方法提修改

2.读内容

  sp = getSharedPreferences("UserInfo", );
etAccount.setText(sp.getString("account", null));
etPW.setText(sp.getString("password", null));
cbal.setChecked(sp.getBoolean("cbal", false));
cbrp.setChecked(sp.getBoolean("cbrp", false));

Android SharedPreferences登录记住密码的更多相关文章

  1. android: SharedPreferences实现记住密码功能

    既然是实现记住密码的功能,那么我们就不需要从头去写了,因为在上一章中的最佳实 践部分已经编写过一个登录界面了,有可以重用的代码为什么不用呢?那就首先打开 BroadcastBestPractice 项 ...

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

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

  3. 通过sharedpreferences实现记住密码功能

    通过sharedpreferences实现记住密码功能

  4. Android之登录时密码的保护

    在很多的Android项目中都需要用户登录.注册.这样的话在开发中做好保护用户密码的工作就显得尤为重要.这里我把自己的密码保护方法记录下来. 这是我建了一个保存密码的文件,以便于检查自己保存密码或者上 ...

  5. Cookie实现登录记住密码

    Cookie实现记住登录密码,用户可以自由选择是否记住密码,或者用户之前选择记住了,但是某一次又不想记住了,需要将之前对应的Cookie删除掉 Cookie相当于map 也是键值对的形式,但是并不相同 ...

  6. QT 登录记住密码方法之一:Qt QSettings读写配置文件

    不过本文写的是明文保存,最好还是加密一下,以防文件被非法读取 /**登录初始化的时候处理这部分操作*/ Settings cfg("user.ini",QSettings::Ini ...

  7. vue 登录 + 记住密码 + 密码加密解密

    <template> <el-form :model="ruleForm"> <h3 class="title">系统登录& ...

  8. JavaScript登录记住密码操作

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http ...

  9. SharedPreferences实现记住密码功能

    SharedPerferences 简单介绍 用于保存简单的键值对数据: 它将数据放在 /data/data/<package name>/shared_prefs目录下,用xml文件保存 ...

随机推荐

  1. Ubuntu 添加桌面快捷方式

    使用Linux Desktop Entry创建 ~$ cd ~/Desktop/ ~$ vim AndroidStudio.desktop 插入以下代码 [Desktop Entry] Encodin ...

  2. Delphi系统托盘组件 TTrayIcon 简介

    TTrayIcon 的主要属性: TrayIcon.Icon指定托盘图标, 有几种用法:1.设计时选择;2.把一个 TIcon 对象给它;3.使用当前程序图标: TrayIcon1.Icon := A ...

  3. android shape的使用详解以及常用效果(渐变色、分割线、边框、半透明阴影效果等)

    shape使用.渐变色.分割线.边框.半透明.半透明阴影效果. 首先简单了解一下shape中常见的属性.(详细介绍参看  api文档 ) 转载请注明:Rflyee_大飞: http://blog.cs ...

  4. mysql批量删除指定前缀或后缀表

    今天突然发现我们数据库中多出很多表,后缀名为"copy",预计是navicat直接拷贝导致的,然后要对这些有同样后缀名的表进行删除,假设一个一个选择会非常麻烦,表计较多,在网上找了 ...

  5. Lucene全文检索

    Lucene写入和更新操作: if (id.equals("")) { this.goodsService.save(goods); String goods_lucene_pat ...

  6. Codeforces-Div312

    题意:给你n个数,进行*2,/2操作,求解最小操作次数能使所有数相同. 思路:因为数值在100000以内,直接枚举过去,对读入的每一个数,模拟操作,用数组s来存放累计操作步数,数组flag用来标记确 ...

  7. ASPNET5的依赖注入

    ASP.NET5设计的时候就是以DI为基础的,它可以利用内建的框架在Startup类的方法中,把依赖注入进去.应用服务也可以被配置的注入.默认的服务容器提供一些基本的功能,它并不打算代替现代主流的DI ...

  8. Android开源项目 Universal imageloader 源码研究之Lru算法

    https://github.com/nostra13/Android-Universal-Image-Loader universal imageloader 源码研究之Lru算法 LRU - Le ...

  9. 使用WebUploader使用,及使用后测试横拍或竖拍图片图片方向不对等解决方案

    WebUploader是由Baidu WebFE(FEX)团队开发的一个简单的以HTML5为主,FLASH为辅的现代文件上传组件.在现代的浏览器里面能充分发挥HTML5的优势,同时又不摒弃主流IE浏览 ...

  10. protobuf的反射机制

    反射机制 java在运行状态时,能够知道任意类的所有属性和方法,都能够调用任意对象的任意方法和属性.这种动态获取的信息以及动态调用对象的方法的功能称为java语言的反射机制. C++本身没有反射机制. ...