1. 程式人生 > 實用技巧 >筆記之SharedPreferences儲存輕量級資料基本運用

筆記之SharedPreferences儲存輕量級資料基本運用

備註: 本文參考了CSDN上某博主的一篇文章 -----基於SP(SharedPreferences)的基本使用以及實際應用介紹 連結: https://blog.csdn.net/qq_37842258/article/details/70751726

1.SharedPreferences 是android中比較輕量級的儲存資料類:

主要儲存一些常用的配置,如使用者登陸時勾選了記住密碼,則儲存賬號&密碼, 下次進入程式時不用再輸入;

還可以在使用者安裝完某app後,根據儲存的是否是第一次使用此app的狀態,來決定進去app時,是否要載入導航頁給使用者;

2.SharedPreferences的儲存資料:

//第一個引數是儲存的檔案的名字,儲存的檔案是xml格式的,路徑/data/data/<包名>/shared_prefs/xxxx.xml

//第二個引數是檔案讀寫型別,MODE_PRIVATE是私有化,只能被本應用讀寫,外部程式不能訪問,保證了安全性

//SharedPreferences物件本身只能獲取資料而不支援儲存和修改,儲存修改是通過Editor物件實現

//editor無論是儲存、移除、還是清除資料,最後一定都要記得提交

SharedPreferences sp = getSharedPreferences("LoginSettings",MODE_PRIVATE);

SharedPreferences.Editor editor = getSharedPreferences("LoginSettings",MODE_PRIVATE);

editor.putBoolean("IfRemember",true);

editor.putString("Name",str_name);

editor.putString("PWD",str_password);

//editor.commit()// 同步

editor.apply() //非同步

commit和apply都可以用來提交,具體差異看網上有的大神做了分析, 文章 "每日一問:談談 SharedPreferences 的 apply() 和 commit()" 連結https://www.cnblogs.com/liushilin/p/11153041.htmlde

3.SharedPreferences的讀取資料:

SharedPreferences sp = getSharedPreferences("LoginSettings",MODE_PRIVATE);

String name = sp.getString("Name","請輸入姓名")

String password = sp.getString("PWD","請輸入密碼")

下面是一個登入時利用SharedPreference記住密碼的demo

package com.example.sharedpreference_demo;

import androidx.appcompat.app.AppCompatActivity;

import android.content.SharedPreferences;
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;

/*
是否是
1.第一次登陸,
   是否勾選記住密碼
   勾選,將賬號&密碼儲存後,登陸
   不勾選,直接登陸
2.之後登陸,
   如果之前勾選了記住密碼,則直接從儲存資料中讀取賬號密碼,並設定輸入框
   如果之前沒勾選,則手動輸入


 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
   private EditText et_Name;
   private EditText et_PSW;
   private CheckBox checkBox;
   private Button btn_Login;
   Boolean if_remember;
   private SharedPreferences.Editor editor;


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

        et_Name = findViewById(R.id.et_name);
        et_PSW = findViewById(R.id.et_psw);
        checkBox =findViewById(R.id.checkbox_remember);
        btn_Login = findViewById(R.id.btn_login);
        btn_Login.setOnClickListener(this);

       SharedPreferences sp = getSharedPreferences("LoginSettings",MODE_PRIVATE);
       if_remember = sp.getBoolean("IfRemember",false);
       if(if_remember){
           et_Name.setText(sp.getString("Name","請輸入姓名"));
           et_PSW.setText(sp.getString("PWD","請輸入密碼"));
           checkBox.setChecked(true);
       }

    }


    private void Login(){

        String str_name = et_Name.getText().toString().trim();
        String str_password = et_PSW.getText().toString().trim();
        if(TextUtils.isEmpty(str_name)||(TextUtils.isEmpty(str_password))){
            Toast.makeText(MainActivity.this,"使用者名稱和密碼不能為空",Toast.LENGTH_SHORT).show();
            return;
        }

        SharedPreferences sp = getSharedPreferences("LoginSettings",MODE_PRIVATE);
        editor = sp.edit();

        if(checkBox.isChecked()){
            editor.putBoolean("IfRemember",true);
            editor.putString("Name",str_name);
            editor.putString("PWD",str_password);
        }
        else{
            editor.clear();
        }
        editor.apply();
        Toast.makeText(MainActivity.this,"登陸中...",Toast.LENGTH_SHORT).show();

    }


    @Override
    public void onClick(View v) {
        Login();
    }
}
View Code
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">


    <TextView
        android:id="@+id/tv_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        android:text="使用者名稱"
        android:textSize="16sp"
        app:layout_constraintBottom_toBottomOf="@id/et_name"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/et_name"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="@+id/et_psw"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/tv_psw"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        android:text="密碼"
        android:textSize="16sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/tv_name" />

    <EditText
        android:id="@+id/et_psw"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="32dp"
        android:layout_marginLeft="32dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@id/tv_psw"
        app:layout_constraintTop_toBottomOf="@id/et_name" />

    <CheckBox
        android:id="@+id/checkbox_remember"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="64dp"
        android:layout_marginLeft="64dp"
        android:text="記住密碼"
        app:layout_constraintBottom_toBottomOf="@+id/btn_login"
        app:layout_constraintEnd_toStartOf="@+id/btn_login"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/tv_psw"
        app:layout_constraintVertical_bias="1.0" />

    <Button
        android:id="@+id/btn_login"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="100dp"
        android:layout_marginEnd="64dp"
        android:layout_marginRight="64dp"
        android:text="登陸"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/checkbox_remember"
        app:layout_constraintTop_toBottomOf="@id/et_psw" />


</androidx.constraintlayout.widget.ConstraintLayout>
View Code