Detailed explanation of Android SharedPreferences and how to transfer data and switch control between activities

What is Android SharedPreferences

Sharedpreferences is a lightweight storage class on the Android platform, which can be used to save some configuration information of the application. Its essence is to save data in the form of "key-value pairs", and it can also be used as data transfer, switch control, Wait for some functions. Its files are stored in the /data/data//shared_prefs directory. Its advantage is that it will not generate null pointers, Application, and static variables, but its disadvantage is that it is not efficient.
Android's five data storage methods are:

  1. File storage: stored in the form of IO stream, which can be divided into internal and external (sd card, etc.) storage of the mobile phone, which can store large data;
  2. SQLite: lightweight, cross-platform database, all data is stored in a single file on the phone, occupying a small amount of memory;
  3. SharedPreferences: store simple configuration parameters in the form of Map;
  4. ContentProvider: Provide the application's private data to other applications;
  5. Network storage: the data is stored on the server, and the data is obtained by connecting to the network;

Today we focus on the use of SP:

How to use Android SharedPreferences

data storage

1、写数据
	//步骤1:创建一个SharedPreferences及editor
	private SharedPreferences sharedPreferences;
	private SharedPreferences.Editor editor;
	//步骤2:实例化对象
	sharedPreferences = getSharedPreferences("data_storage", Context.MODE_PRIVATE);
    editor = sharedPreferences.edit();
    //步骤3:将要存储的值放入文件--此处列举各种类型的存储
    editor.putString("name","fancy");
    editor.putInt("age","21");
    editor.putBoolean("bool",false);
    //步骤4:提交
    editor.commit();

2、读数据
    private String name;
    private int age;
    private boolean status;
 	name = sharedPreferences.getString("name","");
    age = sharedPreferences.getInt("age",1);
    status = sharedPreferences.getBoolean("bool",false);

3、删除指定数据
	editor.remove("name");
	editor.commit();

4、清空数据
	editor.clear();
	editor.commit();

Things to pay attention to: getSharedPreferences() method
This method receives two parameters. The first parameter is used to specify the name of the SharedPreferences file . If the specified file does not exist, one will be created. The second parameter is used to specify the operation mode , mainly There are several modes to choose from. MODE_PRIVATE is the default operation mode, and the effect is the same as passing in 0 directly. The modes MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE have been deprecated in Android 4.2.

Context.MODE_PRIVATE: 指定该SharedPreferences数据只能被本应用程序读、写
Context.MODE_WORLD_READABLE: 指定该SharedPreferences数据能被其他应用程序读,但不能写
Context.MODE_WORLD_WRITEABLE: 指定该SharedPreferences数据能被其他应用程序读
Context.MODE_APPEND:该模式会检查文件是否存在,存在就往文件追加内容,否则就创建新文件

Data transfer
sp can also transfer data between two activities, or as a switch control, the specific usage of sp has been explained above, let's take a direct example:
MainActivity

import androidx.appcompat.app.AppCompatActivity;

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

public class MainActivity extends AppCompatActivity {
    
    

    private Button btn_save;
    private EditText editText;
    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor editor;

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

        btn_save = (Button) findViewById(R.id.btn_save);
        editText = (EditText) findViewById(R.id.display_save);

        btn_save.setOnClickListener(mOnClickListener);
        sharedPreferences = getSharedPreferences("communication", Context.MODE_PRIVATE);
        editor = sharedPreferences.edit();
    }

    private final View.OnClickListener mOnClickListener = new View.OnClickListener() {
    
    
        @Override
        public void onClick(View view) {
    
    
            int id = view.getId();
            switch (id) {
    
    
                case R.id.btn_save:
                    editor.putString("password",editText.getText().toString());
                    editor.commit();
                    Intent intent = new Intent(MainActivity.this,MainActivity2.class);
                    startActivity(intent);
                    break;
            }

        }
    };

}

activity_main.xml

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:orientation="horizontal">
        <TextView
            android:id="@+id/tv_save"
            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:textSize="20dp"
            android:gravity="center"
            android:text="保存的数据:" />

        <EditText
            android:id="@+id/display_save"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingStart="5dp"
            android:paddingTop="5dp"
            android:paddingEnd="10dp"
            android:paddingBottom="5dp"
            android:singleLine="true" />
    </LinearLayout>

    <Button
        android:id="@+id/btn_save"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="保存"/>

</LinearLayout>

MainActivity2

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity2 extends AppCompatActivity {
    
    

    private SharedPreferences sp_receiver;
    private SharedPreferences.Editor editor;
    private TextView textView;
    private String string;

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

        textView = (TextView) findViewById(R.id.tv_display);
        sp_receiver = getSharedPreferences("communication", Context.MODE_PRIVATE);
        editor = sp_receiver.edit();
        string = sp_receiver.getString("password","s");
        textView.setText(string+" ");
    }
}

activity_main2.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity2">

    <TextView
        android:id="@+id/tv_display"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textSize="20dp"/>
</LinearLayout>

Take a look at the effect
Interface 1:
insert image description here
Interface 2:
insert image description here
SP can not only be used as data storage, but also can be used as a switch between different activities, and can also transfer data between activities.

Guess you like

Origin blog.csdn.net/fancynthia/article/details/123526863