Android用SharedPreferences实现登录注册注销功能

Android用SharedPreferences实现登录注册注销功能

前言

本文用SharedPreferences本地缓存账号信息来实现登录注册功能,以及退出注销功能。

一、本文逻辑

本文的注册登录逻辑如下:

1、注册页面:有账号可以直接去登录页面。没有账号的话填写账号密码,检测账号密码不为空,点击立即注册,保存账号信息,跳转到登录页面。

2、登录页面:首先读取缓存的账号密码和是否记住密码,将账号显示,判断记住密码的标志,为空或false,不显示密码,需要输入密码,为true则直接将缓存的密码显示,选择是否记住密码按钮,将此状态存入缓存,点击登录跳转到主页。

3、主页:首先取缓存,判断是否登录,若没有登录跳转到注册页面。点击退出登录,跳转到注册页;(2)点击注销账号,清除所有缓存,跳转到注册页面。

二、代码

1.布局界面

注册页面 activity_register.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:background="#AB2196F3"
            android:gravity="center"
            android:text="用户注册"
            android:textSize="20dp"
            android:textStyle="bold" />
    </RelativeLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginRight="10dp"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="20dp"
        android:orientation="vertical">
        <EditText
            android:id="@+id/reg_uname"
            android:layout_marginTop="40dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:hint="帐号"/>
        <EditText
            android:id="@+id/reg_pwd"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:inputType="textPassword"
            android:hint="密码"/>
        <EditText
            android:id="@+id/reg_pwd2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:inputType="textPassword"
            android:hint="再次确认密码"/>

        <Button
            android:id="@+id/register_btn"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:background="#AB2196F3"
            android:text="立即注册"/>
        <Button
            android:id="@+id/register_toLogin_btn"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:background="#AB2196F3"
            android:text="已有账号?去登录"/>
    </LinearLayout>

</LinearLayout>

登录界面 activity_login.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:background="#AB2196F3"
            android:gravity="center"
            android:text="用户登录"
            android:textSize="20dp"
            android:textStyle="bold" />
    </RelativeLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="20dp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:orientation="vertical">
        <EditText
            android:id="@+id/login_username"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:hint="账号"/>

        <EditText
            android:id="@+id/login_password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="密码"
            android:inputType="textPassword"
            android:layout_margin="10dp"/>
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp">
            <CheckBox
                android:id="@+id/login_remember"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="记住密码" />
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_centerVertical="true"
                android:clickable="true"
                android:onClick="register"
                android:textColor="#3F51B5"
                android:text="没有账号?立即注册" />
        </RelativeLayout>
        <Button
            android:id="@+id/login_btn"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#AB2196F3"
            android:text="登录"
            android:layout_margin="10dp"/>
    </LinearLayout>
</LinearLayout>

主页面

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="15dp"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="主页!"
        android:textSize="30dp"
        android:layout_centerHorizontal="true"
       android:layout_alignParentTop="true"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="主页内容!"
        android:textSize="30dp"
        android:layout_marginTop="50dp"
        android:layout_below="@id/text"
        android:layout_centerHorizontal="true" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:text="退出登录"
        android:layout_alignParentBottom="true"
        android:onClick="Quit"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:text="注销此账号"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:onClick="zhuxiao"/>

</RelativeLayout>

2.Activity 逻辑

注册页面的逻辑

package com.example.yuan;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

/**
 * Created by Yuan on 2020/8/6 17:08.
 * 包名: com.example.yuan
 * 类说明:注册(按钮的点击事件直接使用 Activity 作为事件监听器)
 */
public class RegisterActivity extends AppCompatActivity implements View.OnClickListener {
    //获取用户名,昵称,密码,确认密码
    private EditText reg_uname,reg_uname2,et_pwd,et_pwd2;
    //获取用户名,昵称,密码,确认密码的值
    private String uname,pwd,pwd2;
    private SharedPreferences sp;
    private SharedPreferences.Editor editor;
private Button btn_reg,btn_toLogin;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        init();//获取界面控件
    }

    //UI组件初始化与事件绑定
    private void init(){
        //UI组件初始化
        reg_uname=findViewById(R.id.reg_uname);
        et_pwd=findViewById(R.id.reg_pwd);
        et_pwd2=findViewById(R.id.reg_pwd2);
        btn_toLogin=findViewById(R.id.register_toLogin_btn);
        btn_reg=findViewById(R.id.register_btn);
        //点击事件绑定
        btn_reg.setOnClickListener(this);
        btn_toLogin.setOnClickListener(this);
    }

//点击事件
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.register_btn:
                //获取参数
                uname=reg_uname.getText().toString().trim();
                pwd=et_pwd.getText().toString().trim();
                pwd2=et_pwd2.getText().toString().trim();
                //判断
                if(uname.equals("") || pwd.equals("") ){
                    Toast.makeText(RegisterActivity.this, "用户名或密码不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }else if(!(pwd.equals(pwd2))){
                    Toast.makeText(RegisterActivity.this,"两次输入密码不一致",Toast.LENGTH_SHORT).show();
                }else {
                    //loginInfo表示文件名
                    sp=getSharedPreferences("loginInfo", MODE_PRIVATE);
                    //获取编辑器
                    editor=sp.edit();
                    //存入注册的用户信息
                    editor.putString("username", uname);
                    editor.putString("password",pwd);
                    //提交修改
                    editor.commit();
                    Toast.makeText(RegisterActivity.this,"注册成功",Toast.LENGTH_SHORT).show();
                    startActivity(new Intent(getApplicationContext(),LoginActivity.class));
                }

                break;
            case R.id.register_toLogin_btn://跳转到登录页面
                startActivity(new Intent(getApplicationContext(),LoginActivity.class));
                finish();
                break;
        }

    }
}

登录页面的逻辑

package com.example.yuan;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

/**
 * Created by Yuan on 2020/8/6 16:12.
 * 包名: com.example.yuan
 * 类说明:登录
 */
public class LoginActivity extends AppCompatActivity {
    private EditText et_uname,et_upwd;//获取用户名,密码
    private CheckBox isRemember;
    private Button login_btn;
    private String username,password,sp_name,sp_pwd;
    private Boolean sp_isRemember;//是否记住密码的标志
    private Context mContext;
    private SharedPreferences sp;
    private SharedPreferences.Editor editor;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        init();//获取界面控件
        //读取缓存数据
        sp=getSharedPreferences("loginInfo", MODE_PRIVATE);
        sp_name=sp.getString("username","");
        sp_pwd=sp.getString("password","");
        sp_isRemember=sp.getBoolean("isRemember",false);
        //如果有账号,直接显示
        Log.d("TAG",sp_name);
        et_uname.setText(sp_name);
        //如果上次登录记住了密码,本次登录直接设置上
        if(sp_isRemember.equals(true)){
            et_upwd.setText(sp_pwd);
            isRemember.setChecked(true);
        }
        mContext= LoginActivity.this;
        //登录按钮的点击事件(直接用匿名内部类)
        login_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //开始登录,获取输入的用户名和密码
               username = et_uname.getText().toString().trim();
               password = et_upwd.getText().toString().trim();
                // TextUtils.isEmpty判断是否输入
                if (TextUtils.isEmpty(username)) {
                    Toast.makeText(mContext, "请输入手机号", Toast.LENGTH_SHORT).show();
                } else if (TextUtils.isEmpty(password)) {
                    Toast.makeText(mContext, "请输入密码", Toast.LENGTH_SHORT).show();
                    // 判断,输入的账号密码,是否与保存在SharedPreferences中一致
                } else if (username.equals(sp_name) && password.equals(sp_pwd)) {
                    //一致登录成功
                    Toast.makeText(mContext, "登录成功", Toast.LENGTH_SHORT).show();
                    //判断记住密码按钮是否选中,选中则将isRemember设置为true,保存状态
                    sp=getSharedPreferences("loginInfo", MODE_PRIVATE);
                    //获取编辑器
                    editor=sp.edit();
                    if (isRemember.isChecked()) {//如果记住密码选中,存入true,否则存入false
                        editor.putBoolean("isRemember",true);
                    }else {
                        editor.putBoolean("isRemember",false);
                    }
                    editor.putBoolean("isLogin",true);//保存登录状态
                    editor.apply();//提交修改
                    //登录成功后关闭此页面进入主页

                    //跳转到主界面,登录成功的状态传递到 MainActivity 中
                    Intent intent=new Intent(getApplicationContext(),MainActivity.class);
                    intent.putExtra("name",username);
                    startActivity(intent);
                    finish();//销毁登录界面
                } else if ((sp_pwd != null && !TextUtils.isEmpty(sp_pwd) && !password.equals(sp_pwd))) {
                    Toast.makeText(mContext, "输入的用户名和密码不一致", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(mContext, "此用户名不存在", Toast.LENGTH_SHORT).show();
                }
            }
        });

    }
    //获取界面控件
    private void init(){
        et_uname=findViewById(R.id.login_username);
        et_upwd=findViewById(R.id.login_password);
        isRemember=findViewById(R.id.login_remember);
        login_btn=findViewById(R.id.login_btn);

    }
//注册按钮的点击事件(直接绑定在控件上)
    public void register(View view) {
        Intent intent=new Intent(getApplicationContext(),RegisterActivity.class);
        startActivity(intent);
    }
}

主页面的逻辑

package com.example.yuan;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private  SharedPreferences sp;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView textView=findViewById(R.id.text);
        Intent intent=getIntent();
        String name=intent.getStringExtra("name");
        sp=getSharedPreferences("loginInfo", MODE_PRIVATE);
        textView.setText("欢迎你,"+name);
        Boolean isLogin=sp.getBoolean("isLogin",false);
        if (!isLogin){
            startActivity(new Intent(getApplicationContext(),RegisterActivity.class));
            finish();
        }else if(TextUtils.isEmpty(name)){
            startActivity(new Intent(getApplicationContext(),LoginActivity.class));
            finish();
        }
    }

    public void Quit(View view) {
        sp=getSharedPreferences("loginInfo", MODE_PRIVATE);
        SharedPreferences.Editor editor=sp.edit();
        editor.putBoolean("isLogin",false);
        editor.commit();
        startActivity(new Intent(getApplicationContext(),RegisterActivity.class));
        finish();
    }
    /**
     * @param view
     */
    public void zhuxiao(View view) {
        sp=getSharedPreferences("loginInfo", MODE_PRIVATE);
        SharedPreferences.Editor editor=sp.edit();
        editor.clear();
        editor.commit();
        Toast.makeText(MainActivity.this,"注销成功",Toast.LENGTH_SHORT).show();
        startActivity(new Intent(getApplicationContext(),RegisterActivity.class));
        finish();
    }

}

总结

在android 中存储数据时经常用SharedPreference, 并且在提交数据时一直用的是Editor的commit方法, 也有用apply方法的。

apply和commit方法的不同:

apply没有返回值而commit返回boolean表明修改是否提交成功
apply是将修改数据原子提交到内存, 而后异步真正提交到硬件磁盘, 而commit是同步的提交到硬件磁盘,因此,在多个并发的提交commit的时候,他们会等待正在处理的commit保存到磁盘后在操作,从而降低了效率。而apply只是原子的提交到内容,后面有调用apply的函数的将会直接覆盖前面的内存数据,这样从一定程度上提高了很多效率。
apply方法不会提示任何失败的提示。

由于在一个进程中,sharedPreference是单实例,一般不会出现并发冲突,如果对提交的结果不关心的话,建议使用apply,当然需要确保提交成功且有后续操作的话,还是需要用commit的。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • Android实现登录注册页面(下)

    前面我们已经完成了登录注册页面的布局,下面我们实现验证登录和记住密码的功能. 我们这里还没用到数据库,所以我们的验证的账号密码,是写死的. 首先进入登录页面,可以从这里跳转到注册页面,注册成功后,账号密码的输入框会自动获取刚刚注册的账号密码,无需再次输入.登录成功后,页面跳转到首页,首页获取并显示刚刚注册的账号,点击首页的退出登录,则返回到登录页面. 接下来,先写首页activity_main.xml页面的内容: <?xml version="1.0" encoding=&quo

  • Android如何通过手机获取验证码来完成注册功能

    注册很多app或者网络账户的时候,经常需要手机获取验证码,来完成注册,那时年少,只是觉得手机获取验证码这件事儿很好玩,并没有关心太多,她是如何实现的,以及她背后的故事到底是什么样子的,现在小编接手的这个项目里面,就需要通过手机号进行注册,并且手机号发送相应的验证码,来完成注册,那么在一些应用app里面到底是如何实现点击按钮获取验证码,来完成注册这整个流程的呢?今天小编就以注册为例,和小伙伴们分享一下,如何通过手机号获取验证码来完成注册的一整套流程以及如何采用正则表达式来验证手机号码是否符合电信.

  • Android客户端实现注册、登录详解(1)

    我们在开发安卓App时难免要与服务器打交道,尤其是对于用户账号信息的注册与登录更是每个Android开发人员必须掌握的技能,本文将对客户端的注册/登录功能的实现进行分析,不到之处还请指出. 在这里我们仅讨论客户端如何请求服务器进行注册,而服务器在收到客户端请求后进行的一系列操作并不在本文所述范围内,有兴趣大家可以参考 请求服务器 客户端在进行用户信息的注册和登录时一般使用post请求(携带参数)去服务器.以volley框架请求服务器为例,真正与服务器进行交互的就是如下代码: StringRequ

  • android实现注册登录程序

    本文实例为大家分享了android实现注册登录程序的具体代码,供大家参考,具体内容如下 注册页面: user_register.xml: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     android:layout_width="fill

  • Android设计登录界面、找回密码、注册功能

    本文实例为大家分享了Android 登录.找回密码.注册功能的实现代码,供大家参考,具体内容如下 1.数据库的设计 我在数据库中添加了两张表,一张表用来存储用户信息,诸如用户名,密码,手机号等,可任意添加.另一张表用来存储上一个登录用户的账户信息,我是为了方便才另外创建了一张表去存储,而且这张表我设计了它只能存储一条信息,每次的存储都是对上一条记录的覆盖.事实上,我尝试过在存储用户信息的那张表内添加一个标识,用来标记上一次登录的是哪一个帐号,但是这样做的话,每次改变标识都需要遍历整张表,十分的麻

  • Android基于Sqlite实现注册和登录功能

    Android中基于Sqlite实现注册和登录功能,供大家参考,具体内容如下 前言 写这篇博客主要是为了巩固一下学的Sqlite知识以及梳理一下这个项目的逻辑 实现逻辑 项目的图片结构图如下 代码 user class public class User {     private String name;    //用户名     private String password;     //密码     public User(String name, String password) {

  • Android实现注册登录界面的实例代码

    本文讲述了在linux命令下导出导入.sql文件的方法.分享给大家供大家参考,具体如下: AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="online.geekgalaxy.layoutlearn

  • Android开发中实现用户注册和登陆的代码实例分享

    在android的应用中越来越多的包含了网络互动功能,这就带来了注册,登陆账号功能.本文完整的介绍对话框的方式实现用户登陆功能. 登陆效果: 应用程序判断当前用户还未登陆,弹出登陆对话框,用户输入账号和密码信息后,传到服务器验证,验证成功后,现实Toast 成功信息,并转到其他界面. 注册效果:用户如没有账号,则点击登陆对话框的 "没有账号,快速注册账号", 弹出注册界面,用户输入注册信息,点击注册按钮,注册成功后,弹出toast信息"注册成功",完成注册后,转到其

  • Android用户注册界面简单设计

    本文实例为大家分享了Android用户注册界面的设计,供大家参考,具体内容如下 I. 实例目标 设计一个用户注册界面,在其中要使用到一些基础控件,如 文本框.编辑框.按钮.复选框等控件 II. 技术分析 首先在布局文件中使用控件的标记来配置所需要的各个控件,然后在 主Activity中获取到该控件,给其添加监听器来监听其操作,最后在控制台输出所操作的内容. III. 实现步骤 在Eclipse中创建 Android项目,名称为 TestUserRegister .设计一个用户注册界面,在其中要使

  • Android实现登录注册功能

    本文实例为大家分享了Android实现登录注册功能的具体代码,供大家参考,具体内容如下 运行环境 Android Studio 总体效果图 一. 设计注册页面的布局 二.完成注册功能 (1) 添加User类 (2)添加 UserManager类 管理用户信息 package com.example.videoplayer; import android.hardware.usb.UsbRequest; import java.io.BufferedReader; import java.io.F

随机推荐