免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1032 | 回复: 0
打印 上一主题 下一主题

Android开发--SharedPreferences详解及实例 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-02-14 17:03 |只看该作者 |倒序浏览
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
  下面通过“记住密码”功能
  四、实例
  效果图如下
(图)Android简单数据存储类SharedPreferences详解及实例Android简单数据存储类SharedPreferences详解及实例
Android简单数据存储类SharedPreferences详解及实例Android简单数据存储类SharedPreferences详解及实例
登录成功后的页面
Android简单数据存储类SharedPreferences详解及实例Android简单数据存储类SharedPreferences详解及实例
当第一次登录点击”记住密码“后,第二次打开时的页面
  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" android:layout_height="fill_parent"
  4.   android:gravity="right" android:layout_gravity="right"
  5.   android:background="@drawable/default_bg" android:orientation="vertical">
  6.   < TableLayout android:layout_width="fill_parent"
  7.   android:layout_height="wrap_content" android:stretchColumns="1">
  8.   < TableRow android:gravity="center" android:layout_gravity="center">
  9.   < ImageView android:layout_width="fill_parent"
  10.   android:layout_height="wrap_content" android:id="@+id/ivlogo"
  11.   >
  12.   < /ImageView>
  13.   < /TableRow>
  14.   < /TableLayout>
  15.   < TableLayout android:layout_width="fill_parent"
  16.   android:layout_height="wrap_content" android:stretchColumns="1">
  17.   < TableRow android:layout_marginTop="100dip">
  18.   < TextView android:layout_width="wrap_content"
  19.   android:layout_marginLeft="20dip" android:gravity="center_vertical"
  20.   android:layout_height="wrap_content" android:id="@+id/tvaccount"
  21.   android:text="帐号:" android:textSize="20sp">
  22.   < /TextView>
  23.   < EditText android:layout_width="70px" android:layout_height="wrap_content"
  24.   android:id="@+id/etaccount" android:layout_marginRight="20dip"
  25.   android:maxLength="20">< /EditText>
  26.   < /TableRow>
  27.   < TableRow android:layout_marginTop="10dip">
  28.   < TextView android:layout_width="wrap_content"
  29.        android:layout_height="wrap_content" android:id="@+id/tvpw"
  30.   android:layout_marginLeft="20dip" android:gravity="center_vertical"
  31.   android:text="密码:" android:textSize="20sp">
  32.   < /TextView>
  33.   < EditText android:layout_width="70px" android:layout_height="wrap_content"
  34.   android:layout_marginRight="20dip" android:id="@+id/etpw"
  35.   android:inputType="textPassword">< /EditText>
  36.   < /TableRow>
  37.   < /TableLayout>
  38.   < LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  39.   android:layout_width="wrap_content" android:layout_height="wrap_content"
  40.   android:orientation="horizontal" android:layout_marginTop="5dip"
  41. android:layout_marginRight="20dip">
  42.   < TextView android:layout_width="wrap_content"
  43.   android:layout_height="wrap_content" android:id="@+id/tvclear"
  44.   android:text="清除Cookies" android:textColor="#aa0000" android:textSize="12px">< /TextView>
  45.   < /LinearLayout>
  46.   < TableLayout android:layout_width="fill_parent"
  47.   android:layout_height="wrap_content" android:layout_marginTop="20dip">
  48.   < TableRow android:gravity="center" android:layout_width="fill_parent">
  49.   < Button android:layout_width="100px" android:layout_height="wrap_content"
  50.   android:id="@+id/btnlogin" android:layout_gravity="center"
  51.   android:text="登录">< /Button>
  52.   < Button android:layout_width="100px" android:layout_height="wrap_content"
  53.   android:id="@+id/btnexit" android:layout_gravity="center"
  54.   android:text="退出">< /Button>
  55.   < /TableRow>
  56.   < /TableLayout>
  57.   < LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  58.   android:layout_width="wrap_content" android:layout_height="wrap_content"
  59.         android:orientation="horizontal" android:layout_marginTop="25dip">
  60.   < CheckBox android:layout_width="wrap_content"
  61.   android:layout_height="wrap_content" android:id="@+id/cbrp"
  62.   android:text="记住密码" android:textSize="12px">< /CheckBox>
  63.   < CheckBox android:layout_width="wrap_content"
  64.   android:layout_height="wrap_content" android:id="@+id/cbal"
  65.   android:text="自动登录" android:textSize="12px">< /CheckBox>
  66.   < /LinearLayout>
  67.   < /LinearLayout>
  java代码
  1.   package com.wjq;
  2.   import android.app.Activity;
  3.   import android.content.Context;
  4.   import android.content.SharedPreferences;
  5.   import android.os.Bundle;
  6.   import android.util.Log;
  7.   import android.view.Display;
  8.   import android.view.View;
  9.   import android.view.View.OnClickListener;
  10.   import android.widget.Button;
  11.   import android.widget.CheckBox;
  12.   import android.widget.CompoundButton;
  13.   import android.widget.EditText;
  14.   import android.widget.TextView;
  15.   import android.widget.Toast;
  16.   import com.wjq.beans.User;
  17.   import com.wjq.func.UserMgr;
  18.   public class Login extends Activity {
  19.   private EditText etAccount;
  20.   private EditText etPW;
  21.   private Button btnLogin;
  22.   private Button btnExit;
  23.   private CheckBox cbrp;
  24.   private CheckBox cbal;
  25.   private UserMgr userMgr;
  26.   private User user;
  27.   private SharedPreferences sp;
  28.   private TextView tvClear;
  29.   /*
  30.   * (non-Javadoc)
  31.   *
  32.   * @see android.app.Activity#onCreate(android.os.Bundle)
  33.   */
  34.   @Override
  35.   protected void onCreate(Bundle savedInstanceState) {
  36.   // TODO Auto-generated method stub

  37.   super.onCreate(savedInstanceState);
  38.   setContentView(R.layout.login);
  39.   etAccount = (EditText) findViewById(R.id.etaccount);
  40.   etPW = (EditText) findViewById(R.id.etpw);
  41.   cbrp = (CheckBox) findViewById(R.id.cbrp);
  42.   cbal = (CheckBox) findViewById(R.id.cbal);
  43.   btnLogin = (Button) findViewById(R.id.btnlogin);
  44.   btnExit = (Button) findViewById(R.id.btnexit);
  45.   tvClear=(TextView)findViewById(R.id.tvclear);
  46.   InitConfig();
  47.   cbrp
  48.   .setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
  49.   @Override
  50.   public void onCheckedChanged(CompoundButton buttonView,
  51.   boolean isChecked) {
  52.   sp = getSharedPreferences("UserInfo", 0);
  53.   sp.edit().putBoolean("cbrp", isChecked).commit();
  54.   }
  55.   });
  56.   cbal
  57.   .setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
  58.   @Override
  59.   public void onCheckedChanged(CompoundButton buttonView,
  60.   boolean isChecked) {
  61.   sp = getSharedPreferences("UserInfo", 0);
  62.   sp.edit().putBoolean("cbal", isChecked).commit();
  63.   }
  64.   });
  65.   btnLogin.setOnClickListener(new OnClickListener() {
  66.   @Override
  67.   public void onClick(View v) {
  68.   user = new User(etAccount.getText().toString(), etPW.getText()
  69.   .toString());
  70.   Log.i("tag", "Account:" + etAccount.getText().toString());
  71.   Log.i("tag", "Password:" + etPW.getText().toString());
  72.   userMgr = new UserMgr();
  73.   Boolean flag = userMgr.CheckUser(user, Login.this);
  74.   if (!flag) {
  75.   Toast.makeText(Login.this, "用户验证错误!", 1000).show();
  76.   }
  77.   else {
  78.   if (cbrp.isChecked()) {
  79.   sp = getSharedPreferences("UserInfo",
  80.   Context.MODE_WORLD_WRITEABLE
  81.   | Context.MODE_WORLD_READABLE);
  82.        sp.edit().putString("account",
  83.   etAccount.getText().toString()).commit();
  84.   sp.edit().putString("password",
  85.   etPW.getText().toString()).commit();
  86.   }
  87.   }
  88.   }
  89.   });
  90.   btnExit.setOnClickListener(new OnClickListener() {
  91.   @Override
  92.   public void onClick(View v) {
  93.   System.exit(0);
  94.   }
  95.   });
  96.   tvClear.setOnClickListener(new OnClickListener(){
  97.   @Override
  98.   public void onClick(View v) {sp=getSharedPreferences("UserInfo", 0);
  99.   sp.edit().clear().commit();
  100.   }});
  101.   }
  102.   //初始化配置

  103.   private void InitConfig() {
  104.   sp = getSharedPreferences("UserInfo", 0);
  105.   etAccount.setText(sp.getString("account", null));
  106.   etPW.setText(sp.getString("password", null));
  107.   cbal.setChecked(sp.getBoolean("cbal", false));
  108.   cbrp.setChecked(sp.getBoolean("cbrp", false));
  109.   }
  110.   }
  说明:
  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));
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP