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

【Android】SharedPreferencesの使い方をサンプルコード付きでわかりやすく解説

AndroidのSharedPreferencesとは?

SharedPreferencesは、Androidアプリで少量のデータを「キーと値(Key-Value)」のペアとして永続的に保存するための標準的な仕組みです。保存されたデータはアプリ内部のファイルに書き込まれるため、アプリを終了して再起動した後でも値が保持されます。ユーザー名やパスワード、各種設定情報の保存などによく利用されます。

この記事では、ログイン画面を例に「名前・パスワード・チェックボックスの状態を保存し、次回起動時に復元する」サンプルを通じて、SharedPreferencesの基本的な使い方をステップごとに解説します。

ステップ1:新規プロジェクトを作成する

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

ステップ2:レイアウトファイル(activity_main.xml)を編集する

res/layout/activity_main.xmlに以下のコードを記述します。画面には、名前入力用のEditText、パスワード入力用のEditText、ログインボタン、そして「認証情報を記憶する」チェックボックスを配置しています。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
   xmlns:tools="https://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
   <EditText
      android:id="@+id/etName"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true"
      android:ems="10"
      android:layout_marginTop="75dp"
      android:hint="Enter Name"/>
   <EditText
      android:id="@+id/etPassword"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_below="@id/etName"
      android:ems="10"
      android:layout_centerHorizontal="true"
      android:hint="Enter Password"/>
   <Button
      android:id="@+id/btnLogin"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Login"
      android:layout_below="@id/etPassword"
      android:layout_alignStart="@id/etPassword"
      android:layout_marginTop="10dp" />
   <CheckBox
      android:id="@+id/checkBox"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_below="@id/btnLogin"
      android:layout_marginTop="10dp"
      android:text="Remember my credentials"
      android:layout_alignStart="@id/btnLogin"/>
</RelativeLayout>

ステップ3:MainActivity.javaを実装する

src/MainActivity.javaに以下のコードを追加します。

import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
   SharedPreferences sharedPreferences;
   SharedPreferences.Editor editor;
   EditText name, password;
   Button button;
   CheckBox checkBox;
   String strName, strPassword, strCheckBox;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      name = findViewById(R.id.etName);
      password = findViewById(R.id.etPassword);
      button = findViewById(R.id.btnLogin);
      checkBox = findViewById(R.id.checkBox);
      sharedPreferences =PreferenceManager.getDefaultSharedPreferences(this);
      editor = sharedPreferences.edit();
      checkSharedPreference();
      button.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            if (checkBox.isChecked()) {
               editor.putString(getString(R.string.checkBox),"True");
               editor.commit();
               strName = name.getText().toString();
               editor.putString(getString(R.string.name), strName);
               editor.commit();
               strPassword = password.getText().toString();
               editor.putString(getString(R.string.password), strPassword);
               editor.commit();
            } else {
               editor.putString(getString(R.string.checkBox),"False");
               editor.commit();
               editor.putString(getString(R.string.name), "");
               editor.commit();
               editor.putString(getString(R.string.password), "");
               editor.commit();
            }
         }
      });
   }
   private void checkSharedPreference(){
      strCheckBox= sharedPreferences.getString(getString(R.string.checkBox), "False");
      strName = sharedPreferences.getString(getString(R.string.name), "");
      strPassword = sharedPreferences.getString(getString(R.string.password), "");
      name.setText(strName);
      password.setText(strPassword);
      if (strCheckBox.equals("True")) {
         checkBox.setChecked(true);
      } else {
         checkBox.setChecked(false);
      }
   }
}

コードのポイント

  • SharedPreferencesの取得:PreferenceManager.getDefaultSharedPreferences(this)でデフォルトのSharedPreferencesインスタンスを取得し、edit()でエディタを生成します。
  • データの保存:putString(キー, 値)で値をセットし、commit()を呼び出すことで保存が確定します。チェックボックスの状態に応じて、入力内容を保存するか空文字でクリアするかを切り替えています。
  • データの復元:起動時にcheckSharedPreference()を呼び出し、保存済みの値をgetString(キー, デフォルト値)で読み込んで、EditTextとCheckBoxへ反映させます。

補足:近年のAndroid開発では、同期的に書き込むcommit()よりも、非同期処理となるapply()の使用が推奨されています。また、androidx環境ではgetSharedPreferences("ファイル名", MODE_PRIVATE)でインスタンスを取得する方法が一般的です。

ステップ4:strings.xmlに文字列リソースを定義する

res/values/strings.xmlを開き、以下のコードを追加します。ここで定義した文字列が、SharedPreferencesのキー名として使用されます。

<resources>
   <string name="app_name">Sample</string>
   <string name="checkBox">Sample.checkbox</string>
   <string name="name">Sample.name</string>
   <string name="password">Sample.password</string>
</resources>

ステップ5:AndroidManifest.xmlを確認する

androidManifest.xmlに以下のコードを記述します。SharedPreferencesの利用に特別な権限は不要ですが、MainActivityが正しく登録されていることを確認しておきましょう。

<?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スマートフォンをPCに接続した状態で、Android StudioのツールバーにあるRun(再生)アイコンをクリックしてください。デバイス選択のダイアログが表示されるので、自分のスマートフォンを選んで実行します。

アプリが起動したら、名前とパスワードを入力し、チェックボックスにチェックを入れてログインボタンを押します。その後、アプリを完全に終了して再度起動すると、前回入力した情報が自動的に復元されていることが確認できます。これがSharedPreferencesによるデータ永続化の基本的な動作です。

【Android】SharedPreferencesの使い方をサンプルコード付きでわかりやすく解説

  1. Android SQLiteでunlikely()関数を使用する方法をわかりやすく解説

    AndroidにおけるSQLiteデータベースとは 実装例に入る前に、まずAndroidにおけるSQLiteデータベースの基本を押さえておきましょう。SQLiteはオープンソースのSQLデータベースエンジンで、デバイス上のテキストファイルとしてデータを保存するのが特徴です。 Androidには標準でSQLiteデータベースの実装が組み込まれており、リレーショナルデータベースが持つすべての機能をサポートしています。また、JDBCやODBCのような接続設定を行う必要がなく、そのまま手軽にデータベースへアクセスできる点も大きなメリットです。 本記事では、Android SQLiteでunlikely

  2. 【Android】ScrollViewでスクロールバーを実装・カスタマイズする方法

    はじめにこの記事では、AndroidアプリでScrollView(スクロールビュー)を使用して、画面の内容が収まらない場合でも上下にスクロールできるようにする方法を、実際のコード例とともにステップ形式で解説します。あわせて、android:scrollbarSize属性を使ってスクロールバーの太さを変更する方法も紹介します。ステップ1:新規プロジェクトを作成するまず、Android Studioを起動し、メニューから「File」→「New Project」を選択して新しいプロジェクトを作成します。必要な設定項目をすべて入力し、プロジェクトのセットアップを完了させてください。ステップ2:acti