SharedPreferences用法

本文介绍了一个简单的登录界面实现,包括用户信息的加载与保存功能,通过使用SharedPreferences进行本地存储。

package com.android.test;
  2 
  3 
  4 import android.app.Activity;
  7 import android.content.Intent;
  8 import android.content.SharedPreferences;
  9 import android.content.SharedPreferences.Editor;
 10 import android.os.Bundle;

 13 import android.view.View;
 15 import android.widget.CheckBox;
 16 import android.widget.EditText;
 17 
 24 
 25 /**
 26  * 登录界面
 27  */
 28 public class LoginActivity extends Activity {
 29 
 30     private static final String PREFS_NAME = "MyUserInfo";
 34     private CheckBox chkSaveInfo;
 35     private EditText txtUserName;
 36     private EditText txtPassword;
 38     
 73     
 74     /** Called when the activity is first created. */
 75     @Override
 76     public void onCreate(Bundle savedInstanceState) {
 77         super.onCreate(savedInstanceState);
 78         setContentView(R.layout.loginview);
 82         chkSaveInfo = (CheckBox) this.findViewById(R.id.chkSaveInfo);
 83         txtUserName = (EditText) this.findViewById(R.id.txtUserName);
 84         txtPassword = (EditText) this.findViewById(R.id.txtPassword);
 87         
 88         LoadUserData();
 89     }
 90 
 91     /** 
 92      * 载入已记住用户信息
 93      */
 94     private void LoadUserData(){
            //载入配置文件
 95         SharedPreferences sp = getSharedPreferences(PREFS_NAME, 0);
            //读取配置文件
 96         if (sp.getBoolean("isSave", false)){
 97             String userName = sp.getString("userName", "");
 98             String userPassword = sp.getString("userPassword", "");
 99             if (!("".equals(userName) && "".equals(userPassword))){
100                 txtUserName.setText(userName);
101                 txtPassword.setText(userPassword);
102                 chkSaveInfo.setChecked(true);
103             }
104         }
105     }  
107     /** 
108      * 保存用户信息
109      */
110     private void SaveUserData(){
            //载入配置文件
111         SharedPreferences sp = getSharedPreferences(PREFS_NAME, 0);
            //写入配置文件
112         Editor spEd = sp.edit();
113         if (chkSaveInfo.isChecked()){
114             spEd.putBoolean("isSave", true);
115             spEd.putString("userName", txtUserName.getText().toString());
116             spEd.putString("userPassword", txtPassword.getText().toString());
117         }
118         else{
119             spEd.putBoolean("isSave", false);
120             spEd.putString("userName", "");
121             spEd.putString("userPassword", "");
122         }
123         spEd.commit();
124     }
209 }

转载于:https://www.cnblogs.com/dachao/archive/2012/05/28/2520981.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值