Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách lưu HashMap vào SharedPreferences trên Android

Giới thiệu

SharedPreferences chỉ hỗ trợ các kiểu dữ liệu cơ bản (String, int, boolean, float, long, Set<String>). Để lưu HashMap<String, Object>, giải pháp phổ biến là serialize thành JSON rồi lưu chuỗi JSON.

Các bước thực hiện

Bước 1: Tạo dự án mới

Android Studio → File → New Project → Empty Activity.

Bước 2: Giao diện (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/rlMain"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="16dp"
    android:orientation="vertical">

    <EditText
        android:id="@+id/etName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Tên"
        android:inputType="text" />

    <EditText
        android:id="@+id/etAge"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Tuổi"
        android:inputType="number" />

    <EditText
        android:id="@+id/etGame"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Game yêu thích"
        android:inputType="text" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:onClick="saveLocal"
        android:text="Lưu cục bộ" />

</LinearLayout>

Bước 3: Code MainActivity (src/MainActivity.java)

package app.com.sample;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;

public class MainActivity extends AppCompatActivity {

    final String MAP_KEY = "map";
    EditText etName, etAge, etGame;

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

        etName = findViewById(R.id.etName);
        etAge = findViewById(R.id.etAge);
        etGame = findViewById(R.id.etGame);

        // Load dữ liệu đã lưu khi mở app
        Map<String, Object> savedMap = loadMap();
        if (savedMap.containsKey("name"))
            etName.setText(Objects.requireNonNull(savedMap.get("name")).toString());
        if (savedMap.containsKey("age"))
            etAge.setText(Objects.requireNonNull(savedMap.get("age")).toString());
        if (savedMap.containsKey("game"))
            etGame.setText(Objects.requireNonNull(savedMap.get("game")).toString());
    }

    public void saveLocal(View view) {
        String name = etName.getText().toString().trim();
        String age = etAge.getText().toString().trim();
        String game = etGame.getText().toString().trim();

        if (name.isEmpty()) {
            etName.setError("*Bắt buộc");
            etName.requestFocus();
        } else if (age.isEmpty()) {
            etAge.setError("*Bắt buộc");
            etAge.requestFocus();
        } else if (game.isEmpty()) {
            etGame.setError("*Bắt buộc");
            etGame.requestFocus();
        } else {
            Map<String, Object> inputMap = new HashMap<>();
            inputMap.put("name", name);
            inputMap.put("age", age);
            inputMap.put("game", game);
            saveMap(inputMap);
            Toast.makeText(this, "Đã lưu!", Toast.LENGTH_SHORT).show();
        }
    }

    // Lưu Map -> JSON String -> SharedPreferences
    private void saveMap(Map<String, Object> inputMap) {
        SharedPreferences prefs = getApplicationContext()
                .getSharedPreferences("MyVariables", Context.MODE_PRIVATE);
        if (prefs != null) {
            JSONObject jsonObject = new JSONObject(inputMap);
            String jsonString = jsonObject.toString();
            SharedPreferences.Editor editor = prefs.edit();
            editor.remove(MAP_KEY).apply();
            editor.putString(MAP_KEY, jsonString);
            editor.commit();
        }
    }

    // Đọc SharedPreferences -> JSON String -> Map
    private Map<String, Object> loadMap() {
        Map<String, Object> outputMap = new HashMap<>();
        SharedPreferences prefs = getApplicationContext()
                .getSharedPreferences("MyVariables", Context.MODE_PRIVATE);
        try {
            if (prefs != null) {
                String jsonString = prefs.getString(MAP_KEY, new JSONObject().toString());
                JSONObject jsonObject = new JSONObject(jsonString);
                Iterator<String> keysItr = jsonObject.keys();
                while (keysItr.hasNext()) {
                    String key = keysItr.next();
                    outputMap.put(key, jsonObject.get(key));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return outputMap;
    }
}

Bước 4: Manifest (androidManifest.xml)

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="app.com.sample">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</manifest>

Chạy ứng dụng

Kết nối thiết bị, nhấn Run. Nhập thông tin, nhấn "Lưu cục bộ". Đóng app, mở lại → dữ liệu tự động hiển thị.

Cách lưu HashMap vào SharedPreferences trên Android Cách lưu HashMap vào SharedPreferences trên Android

Giải thích luồng dữ liệu

  1. HashMap (Java) → JSONObject (org.json) → JSON String → SharedPreferences (XML file nội bộ).
  2. Ngược lại: SharedPreferences → JSON String → JSONObject → HashMap.

Lưu ý & Best Practices

  • Giới hạn dung lượng: SharedPreferences không dành cho dữ liệu lớn (>几百KB). Dữ liệu lớn → Room Database, DataStore, hoặc File JSON.
  • Kiểu dữ liệu: JSONObject chỉ hỗ trợ String, Number, Boolean, JSONArray, JSONObject, NULL. Object phức tạp cần custom serializer (Gson, Moshi).
  • Thread safety: apply() ghi async, commit() ghi sync. Dùng apply() cho UI thread.
  • Thay thế hiện đại: Jetpack DataStore (Preferences DataStore) hỗ trợ Flow, coroutine, type-safe, migration từ SharedPreferences.
  • Bảo mật: Dữ liệu nhạy cảm (token, password) nên dùng EncryptedSharedPreferences (Security library).

Ví dụ dùng Gson (thư viện Google) - Linh hoạt hơn

// build.gradle: implementation 'com.google.code.gson:gson:2.10.1'

// Save
String json = new Gson().toJson(myHashMap);
prefs.edit().putString(MAP_KEY, json).apply();

// Load
String json = prefs.getString(MAP_KEY, "");
Type type = new TypeToken<HashMap<String, Object>>(){}.getType();
HashMap<String, Object> map = new Gson().fromJson(json, type);