Android 中SharedPreferences的详解

博主前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住也分享一下给大家,
👉点击跳转到网站

一、SharedPreferences 首选项 介绍

  1. 存储软件的配置信息
  2. 存储的信息:很小,简单的数据;比如:自动登录,记住密码,小说app(返回后再次进入还是 原来看的页数),按钮的状态。

特点:当程序运行首选项里面的数据会全部加载进内容。

二、SharedPreferences的简单使用
1.布局文件中,写入两个按钮,保存到SP,和从SP中获取数据
布局代码的文件就不再写了。

2.看MainActivity的代码,里面有注释详解

package com.example.spdemo;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private Button btn_save;
    private Button btn_obtain;

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

        btn_save=findViewById(R.id.btn_save);
        btn_obtain=findViewById(R.id.btn_obtain);

        //保存到SP
        btn_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences sp = getSharedPreferences("onClick", MODE_PRIVATE);
                sp.edit().putString("SoundCode","测点代码").apply();//apply才会写入到xml配置文件里面
            }
        });

        //获取到SP中的数据
        btn_obtain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences sp1 = getSharedPreferences("onClick", MODE_PRIVATE);
                //如果SoundCode,获取的值是空的,则会弹出后面的默认值
                String obtain = sp1.getString("SoundCode", "默认值");
                Toast.makeText(MainActivity.this, obtain, Toast.LENGTH_SHORT).show();
            }
        });
    }
    /**
     *
     *参数1:SP的名字
     *参数2:SP保存时,用的模式,MODE_PRIVATE常规(每次保存都会更新),指定该SharedPreferences数据只能被本应用程序读、写
     *,MODE_APPEND(每次保存都会追加到后面)
     * @Override
     *     public SharedPreferences getSharedPreferences(String name, int mode) {
     *         return mBase.getSharedPreferences(name, mode);
     *     }
     *
     */
}

三、SharedPreferences的实战,实现记录密码和自动登录功能
效果如下:
在这里插入图片描述
1.XML代码如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    tools:context=".MainActivity"
    android:orientation="vertical"
    >
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        >
        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:text="用户名:"
            android:textSize="25sp"
            android:gravity="right"
            />
        <EditText
            android:id="@+id/et_name"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="4"
            />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        >
        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:text="密码:"
            android:textSize="25sp"
            android:gravity="right"
            />
        <EditText
            android:id="@+id/et_password"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="4"
            android:inputType="textPassword"
            />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <CheckBox
            android:id="@+id/ck_password"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="记住密码"
            android:textSize="20sp"
            />
        <CheckBox
            android:id="@+id/ck_login"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="自动登录"
            android:textSize="20sp"
            />

    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        >
        <Button
            android:id="@+id/btn_register"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="注册"
            android:layout_marginLeft="5dp"
            android:layout_marginRight="5dp"
            />
        <Button
            android:id="@+id/btn_login"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="登录"
            android:layout_marginLeft="5dp"
            android:layout_marginRight="5dp"
            />

    </LinearLayout>
</LinearLayout>

2.MainActivity代码如下:详解和注释都已经写好

package com.example.shareddemo;

import androidx.appcompat.app.AppCompatActivity;

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

public class MainActivity extends AppCompatActivity {

    private EditText et_name;
    private EditText et_password;
    private CheckBox ck_password;
    private CheckBox ck_login;
    private Button btn_register;
    private Button btn_login;
    private SharedPreferences sp;

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

        et_name=findViewById(R.id.et_name);
        et_password=findViewById(R.id.et_password);
        ck_password=findViewById(R.id.ck_password);
        ck_login=findViewById(R.id.ck_login);
        btn_register=findViewById(R.id.btn_register);
        btn_login=findViewById(R.id.btn_login);
         sp = getSharedPreferences("Personal", MODE_PRIVATE);
        //登录方法
        LoginMethod();
        //程序再次进入获取SharedPreferences中的数据
        AgainInto();
    }

    private void AgainInto() {
        //如果获取为空就返回默认值
        boolean ck1 = sp.getBoolean("ck_password", false);
        boolean ck2 = sp.getBoolean("ck_login", false);

        //如果是记住密码
        if (ck1){
            String name=sp.getString("name","");
            String password=sp.getString("password","");
            et_name.setText(name);
            et_password.setText(password);
            //记住密码打上√
            ck_password.setChecked(true);
        }
        //如果是自动登录
        if (ck2){
            ck_login.setChecked(true);
            Toast.makeText(this, "我是自动登录!", Toast.LENGTH_SHORT).show();
        }
    }

    private void LoginMethod() {
        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name=et_name.getText().toString().trim();
                String password=et_password.getText().toString().trim();
                //判断用户名和密码是否为空
                if (TextUtils.isEmpty(name)||TextUtils.isEmpty(password)){
                    Toast.makeText(MainActivity.this, "用户名和密码不能为空", Toast.LENGTH_SHORT).show();
                }else {
                    //如果记录密码是勾选的
                    if (ck_password.isChecked()){
                        //把用户名和密码保存在SharedPreferences中
                        sp.edit().putString("name",name).apply();
                        sp.edit().putString("password",password).apply();
                        sp.edit().putBoolean("ck_password",true).apply();
                    }else {//没有勾选,保存空值
                        sp.edit().putString("name","").apply();
                        sp.edit().putString("password","").apply();
                        sp.edit().putBoolean("ck_password",false).apply();
                    }
                    //如果自动登录是勾选的
                    if (ck_login.isChecked()){
                        sp.edit().putBoolean("ck_login",true).apply();
                    }else {
                        sp.edit().putBoolean("ck_login",false).apply();
                    }
                }
            }
        });

    }
}

以上就是SharedPreferences类的基本使用,记录,学习,和总结~ 一直在路上

  • 29
    点赞
  • 163
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

路宇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值