Android开发学习(5)记住用户名密码,自动登录

本文介绍如何在Android应用中使用SharedPreferences实现记住用户名和密码功能,从而达到自动登录的效果。通过学习SharedPreferences的基本操作,如初始化、获取和设置键值对,改造登录页面并增加相关选项,提升用户体验。同时指出,出于安全考虑,敏感信息通常在服务器端加密处理。
摘要由CSDN通过智能技术生成

上篇文章我们学习编写了一个简单的登录页面,本篇文章,我们继续丰富这个页面,实现自动登录和记住用户名密码,学习安卓一个简单的数据存储器SharedPreferences使用。

SharedPreferences

SharedPreferences是Android中最容易理解的数据存储技术,实际上SharedPreferences处理的就是一个基于XML文件存储key-value(键值对)。SharedPreferences常用来存储一些轻量级的数据. 其存储位置在/data/data/<包名>/shared_prefs目录下。SharedPreferences对象本身只能获取数据而不支持存储和修改,存储修改是通过Editor对象实现。

初始化

spUser = this.getSharedPreferences(spName, Context.MODE_PRIVATE);

获取键值对

spUser.getString(spKeyUser, "")

设置键值对

SharedPreferences.Editor editor = spUser.edit();
editor.putString(spKeyUser, userid);
editor.putString(spKeyPass,pass);
editor.commit();

登录页面

增加记住用户名密码,自动登录多选框
login-auto

<?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:background="#2197db"
>

    <TextView
            android:text="XS-TestApp"
            android:id="@+id/loginbutton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="90dp"
            android:layout_marginBottom="20dp"
            android:textColor="#fffefe"
            android:textSize="30sp"/>

    <LinearLayout
            android:id="@+id/input"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/loginbutton"
            android:layout_marginLeft="28dp"
            android:layout_marginRight="28dp"
            android:background="#fff"
            android:orientation="vertical">
        <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="44dp"
                android:background="#fff"
                android:gravity="center_vertical"
                android:orientation="horizontal" >

            <EditText
                    android:id="@+id/userId"
                    android:layout_width=
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值