Android: MMKV – Key-Value Store

Directory

1. Introduction to MMKV

1. Features and advantages:

2. User Guide:

3. Dependent packages:

Second, the common method of MMKV

1. Initialize and obtain the instance:

2. Store data:

3. Read data

4. Delete data

5. Other operations:

3. Examples of MMKV usage

MainActivity:

activity_main:

operation result:

4. Comparison between MMKV and SharedPreferences

1. Introduction to MMKV

MMKV is a lightweight key-value store library for the Android platform, which provides an efficient and reliable way to store and read data in applications.

1. Features and advantages:

  • High performance: Compared with traditional storage methods such as SharedPreferences and SQLite, MMKV has excellent performance.
  • Lightweight: MMKV is a small library with no external dependencies and is easy to integrate into existing projects.
  • Multi-thread support: MMKV has good multi-thread support, and can safely perform data read and write operations in concurrent scenarios.
  • Ease of use: MMKV provides an easy-to-use API that supports storage and read operations of various data types.
  • Data security: MMKV uses a built-in AES encryption mechanism to protect the security of stored data.

2. User guide:

  1. Import dependencies: Add MMKV dependencies to the project’s build.gradle file.
  2. Initialize MMKV: Initialize the MMKV instance at the entrance of the application, and you can set parameters such as storage path and encryption key.
  3. Store data: Use the putXXX() method to store data in MMKV, supporting various data types.
  4. Read data: Use the getXXX() method to read data from MMKV and perform corresponding type conversion.
  5. Other operations: MMKV also provides operations such as deleting specific key values and clearing all data.

3. Dependent package:

?dependencies {
   implementation 'com.tencent:mmkv:1.2.10'

}

2. Common methods of MMKV

1. Initialize and obtain instance:

String rootDir = MMKV.initialize(context); // Initialize the default root directory
MMKV mmkv = MMKV.defaultMMKV(); // Get the default MMKV instance

2, store data:

mmkv.encode("key", value); // store data, automatically select the appropriate method according to the type
// Or use a specific type of storage method
mmkv.putInt("intKey", intValue);
mmkv.putLong("longKey", longValue);
mmkv.putFloat("floatKey", floatValue);
mmkv.putBoolean("booleanKey", booleanValue);
mmkv.putString("stringKey", stringValue);
mmkv.putStringSet("setKey", stringSet);

3. Read data

Object value = mmkv.decode("key"); // read data, automatically select the appropriate method according to the type
// Or use a specific type of read method
int intValue = mmkv. getInt("intKey", defaultValue);
long longValue = mmkv. getLong("longKey", defaultValue);
float floatValue = mmkv. getFloat("floatKey", defaultValue);
boolean booleanValue = mmkv. getBoolean("booleanKey", defaultValue);
String stringValue = mmkv. getString("stringKey", defaultValue);
Set<String> stringSet = mmkv.getStringSet("setKey", defaultSet);

4, delete data

mmkv.remove("key"); // Delete the specified key-value pair
mmkv.removeValueForKey("key"); // Same as above, same effect
mmkv.removeValuesForKeys(new String[]{"key1", "key2"}); // Delete multiple key-value pairs
mmkv.clearAll(); // Clear all data

5. Other operations:

boolean contains = mmkv.containsKey("key"); // Determine whether the specified key is included
int count = mmkv.count(); // Get the total number of stored data
String[] allKeys = mmkv.allKeys(); // Get all stored keys

3. Example of using MMKV

MainActivity:

package com.example.mmkvdemo;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Toast;

import com.tencent.mmkv.MMKV;


public class MainActivity extends AppCompatActivity implements CompoundButton. OnCheckedChangeListener {
    EditText password, account;
    Button login, register;
    CheckBox mCheckBox;
    String Password, Account;
    MMKV mmkv;
    String TAG = "MainActivity";

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

        // Initialize MMKV
        String rootDir = MMKV. initialize(this);
        Log.d(TAG, "Path:" + rootDir);

        // Read the saved account and password
        mmkv = MMKV. defaultMMKV();
        if (mmkv. contains("account") & amp; & amp; mmkv. contains("password")) {
            Account = mmkv.decodeString("account", "");
            Password = mmkv.decodeString("password", "");
            account.setText(Account);
            password.setText(Password);
        }
    }

    private void initView() {
        mCheckBox = findViewById(R.id.Login_Remember);
        login = findViewById(R.id.login_btn_login);
        register = findViewById(R.id.login_btn_register);
        password = findViewById(R.id.login_edit_pwd);
        account = findViewById(R.id.login_edit_account);
        mCheckBox.setOnCheckedChangeListener(this);
        register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "Clicked to register", Toast.LENGTH_LONG).show();
            }
        });
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "clicked to log in", Toast.LENGTH_LONG).show();
            }
        });
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            if (!TextUtils.isEmpty(password.getText().toString()) & amp; & amp; !TextUtils.isEmpty(account.getText().toString())) {
                // Storing data
                Account = account. getText(). toString();
                Password = password. getText(). toString();
                mmkv.putString("account", Account); // store data
                mmkv.putString("password", Password);
            }
        } else {
            // Clear saved account and password
            mmkv.removeValuesForKeys(new String[]{"account", "password"});
        }
    }
}

activity_main:

<?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:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
      >

    <RelativeLayout
        android:id="@ + id/login_view"
        android:layout_width="400dp"
        android:layout_height="800dp"
        android:layout_centerInParent="true">

        <Button
            android:id="@ + id/login_btn_register"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_below="@ + id/login_btn_login"
            android:layout_alignParentStart="true"
            android:layout_alignParentLeft="true"
            android:layout_marginTop="10dp"
            android:background="#e52525"
            android:text="Register"
            android:textColor="#ffffff"
            android:textSize="20dp" />

        <Button
            android:id="@ + id/login_btn_login"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_below="@ + id/login_edit_pwd"
            android:layout_alignParentStart="true"
            android:layout_alignParentLeft="true"
            android:layout_marginTop="52dp"
            android:background="#545bcb"
            android:text="Login"
            android:textColor="#ffffff"
            android:textSize="20dp" />

        <EditText
            android:id="@ + id/login_edit_pwd"
            android:layout_width="400dp"
            android:layout_height="60dp"
            android:layout_below="@ + id/login_edit_account"
            android:layout_alignParentStart="true"
            android:layout_alignParentLeft="true"
            android:ems="10"
            android:hint="Please enter your password"
            android:inputType="textPassword"
            android:textColor="#ffff00" />

        <EditText
            android:id="@ + id/login_edit_account"
            android:layout_width="400dp"
            android:layout_height="60dp"
            android:layout_alignParentStart="true"
            android:layout_alignParentLeft="true"
            android:layout_marginTop="20dp"
            android:hint="Please enter your username"
            android:inputType="textPersonName"
            android:textColor="#ffff00" />

        <CheckBox
            android:id="@ + id/Login_Remember"
            android:layout_width="100dp"
            android:layout_height="20dp"
            android:layout_below="@ + id/login_edit_pwd"
            android:layout_alignParentStart="true"
            android:layout_alignParentLeft="true"
            android:checked="false"
            android:text="Remember password"
            android:textSize="15dp" />

        <TextView
            android:id="@ + id/login_text_change_pwd"
            android:layout_width="65dp"
            android:layout_height="20dp"
            android:layout_below="@ + id/login_edit_pwd"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            android:text="forgot password"
            android:textSize="15dp" />
    </RelativeLayout>
</LinearLayout>

Run result:

4. Comparison between MMKV and SharedPreferences

MMKV has the following advantages over SharedPreferences (sp):

1. Better performance: MMKV uses a custom key-value storage engine, and the bottom layer uses mmap to map files, avoiding the overhead of memory copy and serialization/deserialization. In contrast, SharedPreferences is based on XML file storage, which requires IO operations for each read and write, and has low performance.

2. Larger storage capacity: MMKV supports storing data in independent files, and can set the maximum size of a single file, while SharedPreferences stores data in an XML file. When the amount of stored data is large, the performance will fall.

3. Multi-process concurrent security: MMKV implements multi-process concurrent secure access through the file lock mechanism, avoiding data confusion and conflicts. However, SharedPreferences does not provide the guarantee of multi-process concurrency security. When multiple processes operate on the same SharedPreferences file at the same time, data exceptions may occur.

4. Support custom encryption: MMKV supports custom encryptors, which can encrypt and protect stored data to increase data security. However, SharedPreferences does not directly support encryption, requiring developers to manually encrypt the stored data.

5. The API is more concise and easy to use: MMKV provides a concise and easy-to-use API, which is more convenient and quick to use, and can directly store various types of data without manual type conversion. SharedPreferences requires manual type conversion and key-value splicing.

In general, MMKV has obvious advantages over SharedPreferences in terms of performance, storage capacity, multi-process concurrency security, and encryption. It is especially suitable for data storage requirements in high-performance requirements, large-scale data storage, or multi-process scenarios. .