SharedPreferences是Android中最容易理解的数据存储技术,实际上SharedPreferences处理的就是一个key-value(键值对)SharedPreferences常用来存储一些轻量级的数据。

代码如下:

 1 //实例化SharedPreferences对象(第一步) 
 2 SharedPreferences mySharedPreferences= getSharedPreferences("test", 
 3 Activity.MODE_PRIVATE); 
 4 //实例化SharedPreferences.Editor对象(第二步) 
 5 SharedPreferences.Editor editor = mySharedPreferences.edit(); 
 6 //用putString的方法保存数据 
 7 editor.putString("name", "Karl"); 
 8 editor.putString("habit", "sleep"); 
 9 //提交当前数据 
10 editor.commit(); 
11 //使用toast信息提示框提示成功写入数据 
12 Toast.makeText(this, "数据成功写入SharedPreferences!" , 
13 Toast.LENGTH_LONG).show(); 

执行以上代码,SharedPreferences将会把这些数据保存在test.xml文件中,可以在File Explorer的data/data下导出该文件,并查看。 
那么已经保存好的数据如何读取出来呢。我们来看:

 1 //同样,在读取SharedPreferences数据前要实例化出一个SharedPreferences对象 
 2 SharedPreferences sharedPreferences= getSharedPreferences("test", Activity.MODE_PRIVATE); 
 3 // 使用getString方法获得value,注意第2个参数是value的默认值 
 4 String name =sharedPreferences.getString("name", ""); 
 5 String habit =sharedPreferences.getString("habit", ""); 
 6 //使用toast信息提示框显示信息 
 7 Toast.makeText(this, "读取数据如下:"+"\n"+"name:" + name + "\n" + "habit:" + habit, Toast.LENGTH_LONG).show();

程序源代码如下:

 1 public class Main extends Activity 
 2 { 
 3 @Override 
 4 public void onCreate(Bundle savedInstanceState) 
 5 { 
 6 super.onCreate(savedInstanceState); 
 7 setContentView(R.layout.main); 
 8 } 
 9 
10 public void onClick_WriteData(View view) 
11 { 
12 SharedPreferences mySharedPreferences = getSharedPreferences("test", 
13 Activity.MODE_PRIVATE); 
14 SharedPreferences.Editor editor = mySharedPreferences.edit(); 
15 editor.putString("name", "karl"); 
16 editor.putString("habit", "sleep"); 
17 editor.commit(); 
18 Toast.makeText(this, "数据成功写入SharedPreferences!" , 
19 Toast.LENGTH_LONG).show(); 
20 
21 } 
22 public void onClick_ReadData(View view) 
23 { 
24 SharedPreferences sharedPreferences = getSharedPreferences("test", 
25 Activity.MODE_PRIVATE); 
26 String name = sharedPreferences.getString("name", ""); 
27 String habit = sharedPreferences.getString("habit", ""); 
28 
29 Toast.makeText(this, "读取数据如下:"+"\n"+"name:" + name + "\n" + "habit:" + habit, 
30 Toast.LENGTH_LONG).show(); 
31 
32 } 
33 } 

运行结果如下:

 

同样,如果设置记住密码,自动登录等复选框,也是将用户输入的数据进行保存,保存在xml文件中,再从中进行读取,如果正确,直接进入下一个成功后的界面,当用户下一次进入时,首先判断输入的文本在xml中有没有记录,如果有记录,就直接从xml文件中读取,实现了记住密码的功能。这里不再进行详细阐述。

1:LoginActivity的代码如下:

  1 package com.liu.activity;
  2 
  3 import android.app.Activity;
  4 import android.content.Context;
  5 import android.content.Intent;
  6 import android.content.SharedPreferences;
  7 import android.content.SharedPreferences.Editor;
  8 import android.os.Bundle;
  9 import android.view.View;
 10 import android.view.View.OnClickListener;
 11 import android.view.Window;
 12 import android.widget.Button;
 13 import android.widget.CheckBox;
 14 import android.widget.CompoundButton;
 15 import android.widget.CompoundButton.OnCheckedChangeListener;
 16 import android.widget.EditText;
 17 import android.widget.ImageButton;
 18 import android.widget.Toast;
 19 
 20 public class LoginActivity extends Activity {
 21     
 22     private EditText userName, password;
 23     private CheckBox rem_pw, auto_login;
 24     private Button btn_login;
 25     private ImageButton btnQuit;
 26     private String userNameValue,passwordValue;
 27     private SharedPreferences sp;
 28 
 29     public void onCreate(Bundle savedInstanceState) {
 30         super.onCreate(savedInstanceState);
 31         
 32         //去除标题
 33         this.requestWindowFeature(Window.FEATURE_NO_TITLE);
 34         setContentView(R.layout.login);
 35         
 36         //获得实例对象
 37         sp = this.getSharedPreferences("userInfo", Context.MODE_WORLD_READABLE);
 38         userName = (EditText) findViewById(R.id.et_zh);
 39         password = (EditText) findViewById(R.id.et_mima);
 40         rem_pw = (CheckBox) findViewById(R.id.cb_mima);
 41         auto_login = (CheckBox) findViewById(R.id.cb_auto);
 42         btn_login = (Button) findViewById(R.id.btn_login);
 43         btnQuit = (ImageButton)findViewById(R.id.img_btn);
 44         
 45         
 46         //判断记住密码多选框的状态
 47       if(sp.getBoolean("ISCHECK", false))
 48         {
 49           //设置默认是记录密码状态
 50           rem_pw.setChecked(true);
 51              userName.setText(sp.getString("USER_NAME", ""));
 52              password.setText(sp.getString("PASSWORD", ""));
 53              //判断自动登陆多选框状态
 54              if(sp.getBoolean("AUTO_ISCHECK", false))
 55              {
 56                     //设置默认是自动登录状态
 57                     auto_login.setChecked(true);
 58                    //跳转界面
 59                 Intent intent = new Intent(LoginActivity.this,LogoActivity.class);
 60                 LoginActivity.this.startActivity(intent);
 61              }
 62         }
 63         
 64         // 登录监听事件  现在默认为用户名为:xuyinghui 密码:123
 65         btn_login.setOnClickListener(new OnClickListener() {
 66 
 67             public void onClick(View v) {
 68                 userNameValue = userName.getText().toString();
 69                 passwordValue = password.getText().toString();
 70                 
 71                 if(userNameValue.equals("xuyinghui")&&passwordValue.equals("123"))
 72                 {
 73                     Toast.makeText(LoginActivity.this,"登录成功", Toast.LENGTH_SHORT).show();
 74                     //登录成功和记住密码框为选中状态才保存用户信息
 75                     if(rem_pw.isChecked())
 76                     {
 77                      //记住用户名、密码、
 78                       Editor editor = sp.edit();
 79                       editor.putString("USER_NAME", userNameValue);
 80                       editor.putString("PASSWORD",passwordValue);
 81                       editor.commit();
 82                     }
 83                     //跳转界面
 84                     Intent intent = new Intent(LoginActivity.this,LogoActivity.class);
 85                     LoginActivity.this.startActivity(intent);
 86                     //finish();
 87                     
 88                 }else{
 89                     
 90                     Toast.makeText(LoginActivity.this,"用户名或密码错误,请重新登录", Toast.LENGTH_LONG).show();
 91                 }
 92                 
 93             }
 94         });
 95 
 96         //监听记住密码多选框按钮事件
 97         rem_pw.setOnCheckedChangeListener(new OnCheckedChangeListener() {
 98             public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
 99                 if (rem_pw.isChecked()) {
100                     
101                     System.out.println("记住密码已选中");
102                     sp.edit().putBoolean("ISCHECK", true).commit();
103                     
104                 }else {
105                     
106                     System.out.println("记住密码没有选中");
107                     sp.edit().putBoolean("ISCHECK", false).commit();
108                     
109                 }
110 
111             }
112         });
113         
114         //监听自动登录多选框事件
115         auto_login.setOnCheckedChangeListener(new OnCheckedChangeListener() {
116             public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
117                 if (auto_login.isChecked()) {
118                     System.out.println("自动登录已选中");
119                     sp.edit().putBoolean("AUTO_ISCHECK", true).commit();
120 
121                 } else {
122                     System.out.println("自动登录没有选中");
123                     sp.edit().putBoolean("AUTO_ISCHECK", false).commit();
124                 }
125             }
126         });
127         
128         btnQuit.setOnClickListener(new OnClickListener() {
129             
130             @Override
131             public void onClick(View v) {
132                 finish();
133             }
134         });
135 
136     }
137 }

其中在跳转页面时,增加了进度条。可以让用户知道程序还在进行中。避免纠结自己的程序是否终止。

2:页面布局login.xml:

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:layout_width="fill_parent"
 4     android:layout_height="fill_parent"
 5     android:background="@drawable/login2"
 6     android:orientation="vertical" >
 7 
 8     <RelativeLayout
 9         android:layout_width="fill_parent"
10         android:layout_height="wrap_content" >
11         <ImageButton 
12             android:id="@+id/img_btn"
13             android:layout_width="wrap_content"
14             android:layout_height="wrap_content"
15             android:layout_alignParentRight="true"
16             android:background="@drawable/quit"/>
17 
18         <TextView
19             android:id="@+id/tv_zh"
20             android:layout_width="wrap_content"
21             android:layout_height="35dip"
22             android:layout_marginLeft="12dip"
23             android:layout_marginTop="10dip"
24             android:gravity="bottom"
25             android:text="帐号:"
26             android:textColor="#000000"
27             android:textSize="18sp" />
28 
29         <EditText
30             android:id="@+id/et_zh"
31             android:layout_width="fill_parent"
32             android:layout_height="40dip"
33             android:layout_below="@id/tv_zh"
34             android:layout_marginLeft="12dip"
35             android:layout_marginRight="10dip" />
36 
37         <TextView
38             android:id="@+id/tv_mima"
39             android:layout_width="wrap_content"
40             android:layout_height="35dip"
41             android:layout_below="@id/et_zh"
42             android:layout_marginLeft="12dip"
43             android:layout_marginTop="10dip"
44             android:gravity="bottom"
45             android:text="密码:"
46             android:textColor="#000000"
47             android:textSize="18sp" />
48 
49         <EditText
50             android:id="@+id/et_mima"
51             android:layout_width="fill_parent"
52             android:layout_height="40dip"
53             android:layout_below="@id/tv_mima"
54             android:layout_marginLeft="12dip"
55             android:layout_marginRight="10dip"
56             android:maxLines="200"
57             android:password="true"
58             android:scrollHorizontally="true" />
59 
60         <CheckBox
61             android:id="@+id/cb_mima"
62             android:layout_width="wrap_content"
63             android:layout_height="wrap_content"
64             android:layout_below="@id/et_mima"
65             android:layout_marginLeft="12dip"
66             android:text="记住密码"
67             android:textColor="#000000" />
68 
69         <CheckBox
70             android:id="@+id/cb_auto"
71             android:layout_width="wrap_content"
72             android:layout_height="wrap_content"
73             android:layout_below="@id/cb_mima"
74             android:layout_marginLeft="12dip"
75             android:text="自动登录"
76             android:textColor="#000000" />
77         <Button
78             android:id="@+id/btn_login"
79             android:layout_width="80dip"
80             android:layout_height="40dip"
81             android:layout_below="@id/et_mima"
82             android:layout_alignParentRight="true"
83             android:layout_alignTop="@id/cb_auto"
84             android:layout_marginRight="10dip"
85             android:gravity="center"
86             android:text="登录"
87             android:textColor="#000000"
88             android:textSize="18sp"/>
89 
90         
91     </RelativeLayout>
92     
93     
94 
95 </LinearLayout>

3:页面显示如下:

4:源码下载请访问:https://github.com/xuyinghuicherish/SharedPreferences

posted on 2015-06-30 20:53  星梦缘vs惜  阅读(508)  评论(0编辑  收藏  举报