Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

안드로이드에서 HashMap을 SharedPreferences에 저장하는 방법

이 글에서는 안드로이드에서 HashMap 데이터를 SharedPreferences(공유 기본 설정)에 저장하는 방법을 단계별로 알아봅니다.

SharedPreferences는 기본적으로 String, int, boolean 같은 단순한 타입만 지원하기 때문에 HashMap과 같은 복잡한 자료구조를 직접 저장할 수 없습니다. 가장 널리 사용되는 해결 방법은 HashMap을 JSON 문자열로 변환해 저장하고, 값을 읽어올 때 다시 Map 형태로 파싱하는 것입니다.

1단계 — 새 프로젝트 생성

Android Studio에서 File → New Project를 선택하고, 필요한 정보를 모두 입력해 새 프로젝트를 생성합니다.

2단계 — 레이아웃 작성 (activity_main.xml)

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 이름, 나이, 좋아하는 게임을 입력받는 세 개의 EditText와 저장 버튼으로 구성된 간단한 화면입니다.

<?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="Name"
        android:inputType="text" />
    <EditText
        android:id="@+id/etAge"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Age"
        android:inputType="number" />
    <EditText
        android:id="@+id/etGame"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Favourite game"
        android:inputType="text" />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:onClick="saveLocal"
        android:text="save local" />
</LinearLayout>

3단계 — 메인 액티비티 구현 (MainActivity.java)

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 mapKey = "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);
        Map<String, Object> outputMap = loadMap();
        if (outputMap.containsKey("name"))
        etName.setText(Objects.requireNonNull(outputMap.get("name")).toString());
        if (outputMap.containsKey("age"))
            etAge.setText(Objects.requireNonNull(outputMap.get("age")).toString());
        if (outputMap.containsKey("game"))
            etGame.setText(Objects.requireNonNull(outputMap.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("*required");
            etName.requestFocus();
        } else if (age.isEmpty()) {
            etAge.setError("*required");
            etAge.requestFocus();
        } else if (game.isEmpty()) {
            etGame.setError("*required");
            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(getApplicationContext(), "Saved Locally!", Toast.LENGTH_SHORT).show();
        }
    }
    private void saveMap(Map<String, Object> inputMap) {
        SharedPreferences pSharedPref = getApplicationContext().getSharedPreferences("MyVariables",
            Context.MODE_PRIVATE);
        if (pSharedPref != null) {
            JSONObject jsonObject = new JSONObject(inputMap);
            String jsonString = jsonObject.toString();
            SharedPreferences.Editor editor = pSharedPref.edit();
            editor.remove(mapKey).apply();
            editor.putString(mapKey, jsonString);
            editor.commit();
        }
    }
    private Map<String, Object> loadMap() {
        Map<String, Object> outputMap = new HashMap<>();
        SharedPreferences pSharedPref = getApplicationContext().getSharedPreferences("MyVariables",
            Context.MODE_PRIVATE);
        try {
            if (pSharedPref != null) {
                String jsonString = pSharedPref.getString(mapKey, (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;
    }
}

핵심 로직 살펴보기

  • saveMap() — 입력받은 HashMap을 JSONObject로 변환한 뒤 문자열로 만들어 SharedPreferences에 저장합니다. 저장 전에 기존 값을 제거(remove)해 데이터가 꼬이지 않도록 처리합니다.
  • loadMap() — SharedPreferences에 저장된 JSON 문자열을 읽어와 키를 하나씩 순회하며 다시 HashMap으로 복원합니다.
  • onCreate() — 앱이 시작될 때 loadMap()을 호출해 이전에 저장한 이름·나이·게임 값을 화면에 자동으로 채워 넣습니다.

4단계 — 매니페스트 설정 (AndroidManifest.xml)

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>

앱 실행 및 결과 확인

실제 안드로이드 기기가 컴퓨터에 연결되어 있다고 가정하고 앱을 실행해 보겠습니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run ▶ 아이콘을 클릭하세요. 목록에서 자신의 모바일 기기를 선택하면 기기 화면에 아래와 같은 기본 화면이 표시됩니다.

안드로이드에서 HashMap을 SharedPreferences에 저장하는 방법