Android - SharedPreferences storage (including source code download)

Android system provides a lightweight data storage --SharedPreferences storage. It shields the underlying file operations, by providing a simple programming interface to application developers, the easiest way to implement the data is stored permanently. This approach is mainly to save a small amount of data, such as configuration information for the application, subject of mobile applications, game players and other points to be saved.

How to use SharedPreferences store data?

First, access to SharedPreferences objects, there are two ways
Method 1:getSharedPreferences(String name, int mode)
name: name of the shared files (not including the extension), the file is in XML format.
mode: used to specify access privileges, its parameter values can be MODE_PRIVATE, MODE_MULTI_PROCESS, generally used first to.
Method 2:getPreferences(int mode)
the same mode and Method 1.

Second, the object is obtained SharedPreferences.Editor, writing by a method Editor object.
Object obtained Editor: SharedPreferences.Editor editor=getSharedPreferences("myinfo",MODE_PRIVATE).edit();
writing data (writing by way key): editor.putString("VALUE","hello");
Submit the current data:editor.commit();

Third, access to the object sharedPreferences SharedPreferences, the data read operation by SharedPreferences
obtaining SharedPreferences objects: SharedPreferences sharedPreferences = getSharedPreferences("myinfo",MODE_PRIVATE);
read the data: sharedPreferences.getString ( "VALUE", " myinfo")

One example of the experience SharedPreferences store by.
This time to show through a simple user login interface, with SharedPreferences store to store account and password information.
Here Insert Picture Description
Code is as follows:
activity_main.xml

<?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">

    <EditText
        android:id="@+id/et_user"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="5dp"
        android:layout_marginLeft="5dp"
        android:layout_marginEnd="5dp"
        android:layout_marginRight="5dp"
        android:layout_marginBottom="10dp"
        android:drawableRight="@drawable/icon_user"
        android:ems="10"
        android:hint="请输入账号"
        android:inputType="textPersonName"
        android:paddingLeft="5dp"
        android:paddingRight="10dp"
        android:textSize="25sp"
        app:layout_constraintBottom_toTopOf="@+id/et_password"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <EditText
        android:id="@+id/et_password"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="5dp"
        android:layout_marginLeft="5dp"
        android:layout_marginEnd="5dp"
        android:layout_marginRight="5dp"
        android:drawableRight="@drawable/icon_password"
        android:ems="10"
        android:hint="请输入密码"
        android:inputType="textPassword"
        android:paddingLeft="5dp"
        android:paddingRight="10dp"
        android:textSize="25sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btn_confirm"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:text="保存并显示用户信息"
        android:textSize="14sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/et_password" />

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toTopOf="@+id/et_user"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@mipmap/ic_launcher_round" />

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java

package com.example.mydemo;

import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
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;

public class MainActivity extends AppCompatActivity {
    public static final String USER = "user";
    public static final String PASSWORD = "password";
    public static final String MYINFO = "myinfo";

    private EditText etUser;
    private EditText etPassword;
    private Button btnConfirm;

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

        etUser = findViewById(R.id.et_user);
        etPassword = findViewById(R.id.et_password);
        btnConfirm = findViewById(R.id.btn_confirm);

        btnConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //保存用户信息
                savedInfo();

                //通过对话框展示存储信息
                showInfo();
            }
        });
    }

    private void showInfo() {
        SharedPreferences sharedPreferences = getSharedPreferences(MYINFO,MODE_PRIVATE);

        //创建一个对话框
        final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("登录信息")
                .setMessage("账户:"+sharedPreferences.getString(USER,MYINFO)+"\n"+
                        "密码:"+sharedPreferences.getString(PASSWORD,MYINFO))
                .setCancelable(false)
                .setNegativeButton("退出", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                })
                .create()
                .show();
    }

    private void savedInfo() {

        if (TextUtils.isEmpty(etUser.getText())&&
                TextUtils.isEmpty(etPassword.getText())) {
            Toast.makeText(getApplicationContext(),"账户或密码不能为空!",Toast.LENGTH_SHORT)
                    .show();
        }
        else {
            SharedPreferences.Editor editor =
                    getSharedPreferences(MYINFO,MODE_PRIVATE).edit();

            editor.putString(USER,etUser.getText().toString());
            editor.putString(PASSWORD,etPassword.getText().toString());
            editor.commit();//提交当前数据

        }

    }
}

Link: Baidu Web site to download extract the code: 5mp7

Published 18 original articles · won praise 5 · Views 8461

Guess you like

Origin blog.csdn.net/qq_43567345/article/details/104406591