Android: SharedPreferences data access

SharedPreferences

Many software have configuration files to store the attribute values of program operation, such as default welcome, login user name and password. The amount of configuration information is not large. If the database is used for storage, the database connection and data operation are time-consuming, which will affect the efficiency of the program. Android provides a shared preferences mechanism to realize lightweight data storage and store information in the form of key,value pairs.

Get SharedPreferences object

There are two ways to get the SharedPreferences object. The first is to get the SharedPreferences object through the getSharedPreferences() method.

public abstract SharedPreferences getSharedPreferences (String name, int mode);
parameter explain
name The name of the saved xml file
mode Operation permission mode of xml document

SharedPreferences has four operating modes:

Operation mode explain
Context.MODE_PRIVATE The default operation mode means that the file is private data and can only be accessed by the application itself. The written content will overwrite the content of the original file
Context.MODE APPEND Check whether the file exists. If it exists, add content to the file, otherwise create a new file
Context.MODE_WORLD_READABLE The current file can be read by other applications
Context.MODE_WORLD_WRITEABLE The current file can be written by other applications

The second is through the preferencemanager The getsharedpreferences (context) method obtains the SharedPreferences object. You cannot specify an xml file name. The file name uses the default form of < package name > + "_preferences. xml".

Data storage and reading

The Editor object of the SharedPreferences interface is used to read and write SharedPreferences data.

public abstract SharedPreferences.Editor edit();

Data is saved through SharedPreferences The putXxx method of the editor interface uploads the key value pair. Where Xxx represents different data types. For example, putString() method is required for value of string type.

public abstract SharedPreferences.Editor putString(String key, String value);

Via SharedPreferences The commit method of the editor interface saves the key value pair. The commit method submits after the event and saves the data in the database.

public abstract boolean commit();

When reading data, obtain the key value of the corresponding key through the key of the SharedPreferences object. Different types of key values have different functions, such as getBoolean, getInt, getFloat and getLong.

public abstract String getString (String key, String defValue);

SharedPreferences sample

Program requirements

Use SharePreferences to write an information book and remember the user name, city, gender and other information. When the APP exits and starts again, the information entered by the user can be displayed.

Code writing

activity_main

<?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="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
    <TextView
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="user name"
        android:textSize="15dp"/>
    <EditText
        android:id="@+id/ename"
        android:layout_width="150sp"
        android:layout_height="40sp">
    </EditText>
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:id="@+id/city"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="city "
            android:textSize="15dp"/>

        <EditText
            android:id="@+id/ecity"
            android:layout_width="150sp"
            android:layout_height="40sp">
        </EditText>

    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <RadioGroup
            android:id="@+id/radioGroup1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >
        <RadioButton
            android:id="@+id/man"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="male" />
        <RadioButton
            android:id="@+id/woman"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="female" />
    </RadioGroup>
    </LinearLayout>
<Button
    android:id="@+id/submit"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Submit">
</Button>

</LinearLayout>

MainActivity

package com.example.share;

import android.content.Context;
import android.content.SharedPreferences;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    private EditText ename;
    private EditText city;
    private RadioGroup rg;
    private RadioButton man;
    private RadioButton woman;
    private RadioButton radioButton;
    private Button button;
    private SharedPreferences preferences;
    private SharedPreferences.Editor editor;
    private String text;

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

        //Bind corresponding layout control
        rg = (RadioGroup) findViewById(R.id.radioGroup1);
        ename = (EditText) findViewById(R.id.ename);
        city = (EditText) findViewById(R.id.ecity);
        man = (RadioButton) findViewById(R.id.man);
        woman=(RadioButton)findViewById(R.id.woman);
        button = (Button) findViewById(R.id.submit);
        SharedPreferences sharedPreferences = getSharedPreferences("test", MODE_PRIVATE);

        //If not empty
        if (sharedPreferences != null) {

            String nname = sharedPreferences.getString("name", "");
            String ecity = sharedPreferences.getString("city", "");
            text = sharedPreferences.getString("sex", "");
            ename.setText(nname);
            city.setText(ecity);
            if (text.toString().equals("male")){
                man.setChecked(true);
            }
            if (text.toString().equals("female")) {
                woman.setChecked(true);
            }
        }

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //1 create SharePreferences object
                radioButton = (RadioButton)findViewById(rg.getCheckedRadioButtonId());
                String name = ename.getText().toString();
                String ecity = city.getText().toString();
                String sex = radioButton.getText().toString();
                SharedPreferences sharedPreferences = getSharedPreferences("test", MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPreferences.edit();

                //2. Create Editor object and write value
                editor.putString("name", name);
                editor.putString("city", ecity);
                editor.putString("sex", sex);

                //3. Submission
                editor.commit();
                Toast.makeText(MainActivity.this, "success", Toast.LENGTH_LONG).show();
            }
        });
    }
}

Operation effect

The effect of opening the APP for the first time is as follows:

After entering the information, open the APP again and the previously entered information will be displayed:

reference material

Android mobile application development, edited by Yang Yi and Deputy edited by Yu dekuang, people's Posts and Telecommunications Press

Keywords: Android

Added by public-image on Sun, 30 Jan 2022 15:41:52 +0200