Android
 Computer >> コンピューター >  >> プログラミング >> Android

【Android】SharedPreferencesにHashMapを保存・読み込みする方法を解説

このチュートリアルでは、AndroidアプリでHashMap(キーと値のペアを持つマップ構造)をSharedPreferencesに保存し、アプリ再起動後も値を復元できるようにする方法を解説します。

SharedPreferencesは本来、Stringやintなどの単純なデータしか保存できません。そこで本記事では、HashMapをJSONObjectでJSON文字列に変換してから保存し、読み込む際に元のマップへ復元するテクニックを使用します。

手順1:新規プロジェクトを作成する

Android Studioを起動し、メニューからFile → New Projectを選択します。必要な項目をすべて入力して、新しいプロジェクトを作成してください。

手順2:レイアウトファイル(activity_main.xml)を編集する

res/layout/activity_main.xmlに以下のコードを追加します。「名前」「年齢」「好きなゲーム」を入力する3つのEditTextと、保存処理を呼び出すButtonを縦方向に配置したシンプルなレイアウトです。

<?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メソッド)のポイント

入力された3つの値をHashMapに格納し、new JSONObject(inputMap)でJSON文字列にシリアライズしています。この文字列をSharedPreferencesに書き込むことで、マップ全体をひとつのエントリとして保存できます。

読み込み処理(loadMapメソッド)のポイント

保存されたJSON文字列を取得し、jsonObject.keys()でイテレータを回しながら各キーと値をoutputMapに詰め直します。これにより、アプリ起動時に入力欄へ前回の値を自動的に復元できます。

手順4:AndroidManifest.xmlを確認する

androidManifest.xmlは以下のようになります。SharedPreferencesの利用に特別なパーミッションは不要です。

<?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スマートフォンをパソコンに接続している前提で進めます。Android Studioでプロジェクト内のアクティビティファイルを開き、ツールバーのRunアイコン【Android】SharedPreferencesにHashMapを保存・読み込みする方法を解説 をクリックします。表示された候補から自分のモバイルデバイスを選択すると、端末に以下のような初期画面が表示されます。

【Android】SharedPreferencesにHashMapを保存・読み込みする方法を解説

各入力欄に値を入力して「save local」ボタンをタップすると「Saved Locally!」というトーストが表示され、データがローカルに保存されます。一度アプリを終了して再度起動すると、入力内容が自動的に復元されていることを確認できます。未入力の項目がある場合は「*required」というエラーが表示され、入力が促される仕組みです。

  1. Androidで指定したURLから画像をダウンロードして表示する方法を徹底解説

    AndroidでURLから画像をダウンロードする方法 このチュートリアルでは、Androidアプリで指定したURLから画像をダウンロードし、画面に表示する方法を段階的に解説します。ネットワーク通信はメインスレッドで行うとアプリがフリーズするため、AsyncTaskを使ってバックグラウンドで処理するのがポイントです。 手順1:新しいプロジェクトを作成する Android Studioを起動し、メニューから「File」→「New Project」を選択して、必要な情報を入力して新しいプロジェクトを作成します。 手順2:レイアウトファイル(activity_main.xml)を編集する res/

  2. AndroidでSharedPreferences(共有プリファレンス)を取得してデータを保存・読み出す方法

    はじめに Androidアプリ開発では、ユーザー名やメールアドレス、各種設定値など、少量のデータを端末内に保存しておきたい場面が多くあります。こうしたデータの永続化に最適なのがSharedPreferences(共有プリファレンス)です。本記事では、SharedPreferencesを使ってデータを保存・取得・クリアする方法を、サンプルコードとともにステップごとに解説します。 SharedPreferencesとは SharedPreferencesは、キーと値(Key-Valueペア)の形式でデータをXMLファイルとして保存する仕組みです。文字列・数値・真偽値などのプリミティブ型データを手軽