登录案例(记住密码)

使用SharedPreferences保存key-value对的步骤如下:
  (1)使用Context类提供的getSharedPreferences()方法,获取SharedPreferences对象。getSharedPreferences()方法的原型如下:

SharedPreferences sp=context.getSharedPreferences(String name, int mode);

  其中,参数name表示存储数据的文件名。有一点需要注意的是,此处只是定义了该文件名,该文件实际上并没有被创建,该文件只有当创建了SharedPreferences.Edit对象并使用该对象的commit()方法提交数据时,才会被创建。参数mode用于指定文件的操作模式,其可选值有四种,如下:
  Context.MODE_APPEND(内容追加模式)、
  Context.MODE_PRIVATE(默认操作模式)、
  Context.MODE_WORLD_READABLE(可读模式)、
  Context.MODE_WORLD_WRITEABLE(可写模式)。

  (2)使用SharedPreferences接口的edit获得SharedPreferences.Editor对象。使用Shared Preferences方式存储数据时需要借助SharedPreferences.Edit类提供的方法来添加数据。

  (3)通过SharedPreferences.Editor接口的putXxx方法保存key-value对。其中Xxx表示不同的数据类型。例如:字符串类型的value需要用putString方法。

  (4)通过SharedPreferences.Editor接口的commit方法保存key-value对。commit方法相当于数据库事务中的提交(commit)操作。
  
案例:
这里写图片描述

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#A4D3EE"
    tools:context="com.example.login123.LoginActivity">

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

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:src="@drawable/deer" />

</RelativeLayout>

activity_two.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_two"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    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="com.example.login123.TwoActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Welcome"
        android:textSize="40sp" />
</RelativeLayout>

login_top.xml:

<?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="match_parent"
    android:orientation="vertical"
    android:padding="32dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/logintop_roundbg"
        android:orientation="vertical"
        android:padding="@dimen/activity_horizontal_margin">

        <EditText
            android:id="@+id/etName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#ffffff"
            android:drawableLeft="@drawable/icon_user"
            android:drawablePadding="10dp"
            android:ems="10"
            android:hint="请输入账号">

            <requestFocus />
        </EditText>

        <EditText
            android:id="@+id/etPassword"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/etName"
            android:layout_marginTop="10dp"
            android:background="#ffffff"
            android:drawableLeft="@drawable/icon_pass"
            android:drawablePadding="10dp"
            android:ems="10"
            android:hint="请输入密码" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/etPassword">

            <CheckBox
                android:id="@+id/cbIsRememberPass"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:layout_weight="1"
                android:text="记住密码"
                android:textSize="20sp" />

            <Button
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:layout_weight="1"
                android:background="#6495ED"
                android:onClick="login"
                android:text="登录" />
        </LinearLayout>
    </LinearLayout>
</RelativeLayout>

该布局主要放置登录所输入的用户名和密码、
LoginActivity.java:

package com.example.login123;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;


public class LoginActivity extends AppCompatActivity {

    private EditText etName;
    private EditText etPassword;
    private CheckBox cbIsRememberPass;
    private SharedPreferences sharedPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initViews();
        sharedPreferences = getSharedPreferences("rememberpassword", Context.MODE_PRIVATE);
        boolean isRemember = sharedPreferences.getBoolean("rememberpassword", false);
        if (isRemember) {
            String name = sharedPreferences.getString("name", "");
            String password = sharedPreferences.getString("password", "");
            etName.setText(name);
            etPassword.setText(password);
            cbIsRememberPass.setChecked(true);
        }
    }

    public void initViews() {
        etName = (EditText) findViewById(R.id.etName);
        etPassword = (EditText) findViewById(R.id.etPassword);
        cbIsRememberPass = (CheckBox) findViewById(R.id.cbIsRememberPass);
    }

    public void login(View view) {
        String name = etName.getText().toString();
        String password = etPassword.getText().toString();
        if ("admin".equals(name) && "123456".equals(password)) {
            SharedPreferences.Editor editor = sharedPreferences.edit();
            if (cbIsRememberPass.isChecked()) {
                editor.putBoolean("rememberpassword", true);
                editor.putString("name", name);
                editor.putString("password", password);
            } else {
                editor.clear();
            }
            editor.commit();
            Intent intent = new Intent(this, TwoActivity.class);
            startActivity(intent);
            finish();
        } else {
            Toast.makeText(this, "账号或密码错误", Toast.LENGTH_LONG);
        }

    }
}

TwoActivity.java:

package com.example.login123;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class TwoActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_two);
    }
}

运行结果:
这里写图片描述
这里写图片描述
这里写图片描述

注意:
SharedPreferences使用很简单,但一定要注意以下几点:
(1)存入数据和删除数据时,一定要在最后使用editor.commit()方法提交数据。
(2)获取数据的key值与存入数据的key值得数据类型要一致,否则查不到数据。
(3)保存SharedPreferences的key值时,可以用静态变量保存,以免储存、删除时写错了。
如:private static final String key=”itcast”;

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值