SharedPreferences实现Android中的数据存储

SharedPreferences是Android平台上一个轻量级的存储类,主要是保存一些常用的配置比如窗口状态,一般在Activity中 重载窗口状态。 它的本质是基于XML文件存储key-value键值对数据,通常用来存储一些简单的配置信息。

其存储位置在/data/data/<包名>/shared_prefs目录下。

SharedPreferences对象本身只能获取数据而不支持存储和修改,存储修改是通过Editor对象实现。

实现SharedPreferences存储的步骤如下:   

一、根据Context获取SharedPreferences对象   

二、利用edit()方法获取Editor对象。   

三、通过Editor对象存储key-value键值对数据。   

四、通过commit()方法提交数据。

实验内容:创建一个登陆页面,含有用户名和密码的登陆验证,通过SharedPreferences技术实现实验中‘记住密码’的技术。点击‘登陆’按钮,实现页面的跳转,并存储登陆用户的用户名和密码。实现,再次登陆时是否记住密码的判断。

1.创建页面布局

通过实验要求需做两个Activity,分别命名为(LoginActivity和ShowActivity)

sharedpreferences存储失败 sharedpreferences如何存储数据_xml


(1.)activity_login加载了login_top和login_bottom的内容

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@drawable/loginbg"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".LoginActivity" >

  <include layout="@layout/login_top"/> 
  <include layout="@layout/login_bottom"/>"

</LinearLayout>

(2.)login_top

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/btnbg_roundcorner"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin" >

    <TextView
        android:id="@+id/tvUsername"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="@string/tvName"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <EditText
        android:id="@+id/etUsername"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/tvUsername"
        android:layout_below="@+id/tvUsername"
        android:background="@android:drawable/edit_text"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <TextView
        android:id="@+id/tvPassword"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/etUsername"
        android:layout_below="@+id/etUsername"
        android:text="@string/tvPassword"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <EditText
        android:id="@+id/etPassword"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/tvPassword"
        android:layout_below="@+id/tvPassword"
        android:layout_marginTop="16dp"
        android:background="@android:drawable/edit_text"
        android:ems="10"
        android:inputType="textPassword" />

    <Button
        android:id="@+id/btnLogin"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/etPassword"
        android:layout_below="@+id/etPassword"
        android:layout_marginTop="20dp"
        android:background="#FF72CAE1"
        android:text="@string/btnLogin" />

    <CheckBox
        android:id="@+id/chkSave"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/btnLogin"
        android:layout_alignBottom="@+id/btnLogin"
        android:layout_alignLeft="@+id/etPassword"
        android:text="@string/chkSave" />

</RelativeLayout>

(3.)login_bottom

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <TextView
        android:id="@+id/tvRegist"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="21dp"
        android:layout_marginTop="18dp"
        android:text="@string/tvRegister"
        android:autoLink="all"
        android:textColorLink="#FF0066CC" />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_marginBottom="24dp"
        android:src="@drawable/panda" />

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="28dp"
        android:src="@drawable/icon" />

</RelativeLayout>

(4.)activity_show

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/RelativeLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/result"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>

将页面布局为如图所示:

sharedpreferences存储失败 sharedpreferences如何存储数据_xml_02


2.在LoginActivity中实现SharedPreferences数据存储,和页面跳转,并作出判断

(1.)通过findView()方法将布局中的所有控件全部实例化;

/*实例化控件*/
    public void findView(){
        etUsername=(EditText) findViewById(R.id.etUsername);
        etPassword=(EditText) findViewById(R.id.etPassword);
        btnLogin=(Button) findViewById(R.id.btnLogin);
        chkSave=(CheckBox) findViewById(R.id.chkSave);
    }

(2.)定义一个内部类ClickHandler实现OnClickListener接口,其目的是为了处理点击‘登陆’时作出事件处理。
在这个内部类中实现了SharedPreferences数据存储,和页面跳转:
①.SharedPreferences数据存储,登陆判断,是否存储判断:

SharedPreferences sharedpreferences=getSharedPreferences("User", MODE_PRIVATE);//获取SharedPreferences对象
            username=etUsername.getText().toString();//获取输入的用户名
            userpassword=etPassword.getText().toString();//获取输入的密码

            if(username.equals("admin")&&userpassword.equals("123456")){//做出事件的判断。如果输入的用户名和密码匹配则执行点击事件

                 Editor editor=sharedpreferences.edit();
                if(chkSave.isChecked()==true){
                    editor.putString("username", username);
                    editor.putString("userpassword", userpassword);
                    editor.putBoolean("rememberpassword", true);
                    Toast.makeText(LoginActivity.this, "用户名密码存储成功", Toast.LENGTH_LONG).show();
            }
                else{
                    Toast.makeText(LoginActivity.this, "没有存储用户名和密码", Toast.LENGTH_LONG).show();
                    editor.clear();//再次登陆时,没有选择记住密码,所以将用户名和密码清空
                }
                editor.commit();//提交事务

②.页面跳转:

/*跳转页面*/
                Intent intent=new Intent();
                intent.setClass(LoginActivity.this,ShowActivity.class);
                Bundle bundle=new Bundle();
                bundle.putString("username", username);
                intent.putExtras(bundle);
                startActivity(intent);
                finish();

(3.)对下次登陆时判断CheckBox是否被选中作出判断:

SharedPreferences sharedpreferences=getSharedPreferences("User", MODE_PRIVATE);
        rememberpassword=sharedpreferences.getBoolean("rememberpassword", false);//读取存储的数据内容,判断复选框是否被选中
        if(rememberpassword){//判断复选框是否被选中
            chkSave.setChecked(true);
            etUsername.setText(sharedpreferences.getString("username", ""));
            etPassword.setText(sharedpreferences.getString("userpassword", ""));

        }

(4.)ShowActivity只作为一个登陆成功页面的显示:

package com.example.minitwittersimulate;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;

public class ShowActivity extends Activity {
    private TextView result;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show);
        Bundle bundle=getIntent().getExtras();
        String usrname=bundle.getString("username");
        result=(TextView) findViewById(R.id.result);
        result.setText("尊敬的"+usrname+"用户,你已经成功登陆");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.show, menu);
        return true;
    }

}

LoginActivity全部代码:

package com.example.minitwittersimulate;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

public class LoginActivity extends Activity {
    private EditText etUsername;
    private EditText etPassword;
    private Button btnLogin;
    private CheckBox chkSave;
    private String username;
    private String userpassword;
    Boolean rememberpassword;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        findView();
        SharedPreferences sharedpreferences=getSharedPreferences("User", MODE_PRIVATE);
        rememberpassword=sharedpreferences.getBoolean("rememberpassword", false);//读取存储的数据内容
        if(rememberpassword){//判断复选框是否被选中
            chkSave.setChecked(true);
            etUsername.setText(sharedpreferences.getString("username", ""));
            etPassword.setText(sharedpreferences.getString("userpassword", ""));

        }
        btnLogin.setOnClickListener(new ClickHandler());
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    /*实例化控件*/
    public void findView(){
        etUsername=(EditText) findViewById(R.id.etUsername);
        etPassword=(EditText) findViewById(R.id.etPassword);
        btnLogin=(Button) findViewById(R.id.btnLogin);
        chkSave=(CheckBox) findViewById(R.id.chkSave);
    }
    /*****
     * 内部类:点击登陆时的事件处理
     * @author Administrator
     *
     */
    class ClickHandler implements OnClickListener
    {
        public void onClick(View v)
        {

            SharedPreferences sharedpreferences=getSharedPreferences("User", MODE_PRIVATE);
            username=etUsername.getText().toString();//获取输入的用户名
            userpassword=etPassword.getText().toString();//获取输入的密码

            if(username.equals("admin")&&userpassword.equals("123456")){//做出事件的判断。如果输入的用户名和密码匹配则执行点击事件

         Editor editor=sharedpreferences.edit();//获取Editor对象
              if(chkSave.isChecked()==true){//记住密码被选中,存储数据
                  editor.putString("username", username);
                  editor.putString("userpassword", userpassword);
                 editor.putBoolean("rememberpassword", true);
                 Toast.makeText(LoginActivity.this, "用户名密码存储成功", Toast.LENGTH_LONG).show();
            }
                else{
                    Toast.makeText(LoginActivity.this, "没有存储用户名和密码", Toast.LENGTH_LONG).show();
                    editor.clear();//再次登陆时,没有选择记住密码,所以将用户名和密码清空
                }
                editor.commit();//提交事务
                /*跳转页面*/
                Intent intent=new Intent();
                intent.setClass(LoginActivity.this,ShowActivity.class);
                Bundle bundle=new Bundle();
                bundle.putString("username", username);//绑定数据
                intent.putExtras(bundle);
                startActivity(intent);
                finish();
            }

            else{
                Toast.makeText(LoginActivity.this, "用户名或密码错误", Toast.LENGTH_LONG).show();
            }


        }
    }
}

运行界面:

sharedpreferences存储失败 sharedpreferences如何存储数据_Text_03


跳转到ShowActivity显示效果:

sharedpreferences存储失败 sharedpreferences如何存储数据_xml_04