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

【Android】SharedPreferencesを使ってアクティビティ間でデータを共有する方法

この記事では、AndroidアプリにおいてSharedPreferences(共有プリファレンス)を使用して、複数のアクティビティ間でデータを受け渡す方法を、実際のサンプルコードとともにステップ形式で解説します。

SharedPreferencesは、キーと値のペア形式で小さなデータを永続的に保存できる仕組みです。Intentでデータを渡す方法とは異なり、一度保存したデータはアプリを終了しても保持されるため、設定情報や一時的な入力値の受け渡しに便利です。

実装の流れ

今回作成するサンプルアプリでは、最初の画面(MainActivity)でEditTextに入力したテキストをSharedPreferencesに保存し、「Next」ボタンをタップすると次の画面(SecondActivity)に遷移して、保存されたテキストを表示します。

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

Android Studioを開き、File → New Projectを選択して、必要な項目をすべて入力し、新しいプロジェクトを作成します。

ステップ2:activity_main.xml にレイアウトを定義する

res/layout/activity_main.xml に以下のコードを追加します。テキスト入力用のEditTextと、画面遷移用のButtonを配置しています。

<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout 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"
   android:layout_margin = "16dp"
   android:orientation = "vertical"
   tools:context = ".MainActivity">
   <EditText
      android:id = "@+id/edit_text"
      android:layout_width = "match_parent"
      android:layout_height = "wrap_content"
      android:layout_gravity = "center"
      android:hint = "Enter something to pass"
      android:inputType = "text" />
   <Button
      android:id = "@+id/button"
      android:layout_width = "wrap_content"
      android:layout_height = "wrap_content"
      android:layout_gravity = "center"
      android:layout_marginTop = "16dp"
      android:text = "Next" />
</LinearLayout>

ステップ3:MainActivity.java に入力値を保存する処理を書く

src/MainActivity.java に以下のコードを追加します。ボタンがクリックされると、EditTextの入力内容を取得し、getSharedPreferences("myKey", MODE_PRIVATE)でSharedPreferencesのインスタンスを取得して「value」というキーで文字列を保存します。その後、SecondActivityへ遷移します。

package com.example.myapplication;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      final EditText editText = findViewById(R.id.edit_text);
      Button button = findViewById(R.id.button);
      button.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            String value = editText.getText().toString().trim();
            SharedPreferences sharedPref = getSharedPreferences("myKey", MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPref.edit();
            editor.putString("value", value);
            editor.apply();
            Intent intent = new Intent(MainActivity.this, SecondActivity.class);
            startActivity(intent);
         }
      });
   }
}

ステップ4:activity_second.xml にレイアウトを定義する

res/layout/activity_second.xml に以下のコードを追加します。保存されたテキストを表示するためのTextViewを配置しています。

<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout 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"
   android:layout_margin = "16dp"
   android:orientation = "vertical"
   tools:context = ".SecondActivity">
   <TextView
      android:id = "@+id/text_view"
      android:layout_width = "match_parent"
      android:layout_height = "wrap_content"
      android:layout_gravity = "center" />
</LinearLayout>

ステップ5:SecondActivity.java で保存した値を読み込む

src/SecondActivity.java に以下のコードを追加します。同じファイル名「myKey」でSharedPreferencesを取得し、getString()メソッドで「value」キーに対応する文字列を読み出してTextViewに表示します。第二引数の空文字列は、キーが存在しない場合のデフォルト値です。

package com.example.myapplication;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class SecondActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_second);
      TextView textView = findViewById(R.id.text_view);
      SharedPreferences sharedPreferences = getSharedPreferences("myKey", MODE_PRIVATE);
      String value = sharedPreferences.getString("value","");
      textView.setText(value);
   }
}

ステップ6:AndroidManifest.xml にアクティビティを登録する

androidManifest.xml に以下のコードを追加します。SecondActivityもapplication要素内に宣言することを忘れないようにしてください。

<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android = "https://schemas.android.com/apk/res/android"
   package = "com.example.myapplication">
   <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>
   <activity android:name = ".SecondActivity"></activity>
   </application>
</manifest>

アプリを実行して動作を確認する

それでは、アプリケーションを実行してみましょう。実機のAndroidスマートフォンをパソコンに接続しているものとして説明します。Android Studioからアプリを実行するには、プロジェクト内のいずれかのアクティビティファイルを開き、ツールバーのRunアイコン 【Android】SharedPreferencesを使ってアクティビティ間でデータを共有する方法 をクリックします。表示された選択肢から接続中のモバイルデバイスを選択すると、端末にデフォルトの画面が表示されます。

【Android】SharedPreferencesを使ってアクティビティ間でデータを共有する方法

最初の画面で任意のテキストを入力して「Next」ボタンをタップすると、次の画面に入力したテキストが表示されれば成功です。このようにSharedPreferencesを使えば、アクティビティ間だけでなく、アプリ再起動後でも同じデータを参照できます。

  1. Androidで複数のアクティビティ(画面)を切り替える方法【サンプルコード付き】

    本記事では、Androidアプリで複数の画面(アクティビティ)をIntentを使って切り替える方法を、サンプルコードとともにわかりやすく解説します。ボタンをタップすると「MainActivity」から「SecondActivity」へ遷移し、そこから再び元の画面へ戻れるというシンプルな例です。 手順1:Android Studioで新規プロジェクトを作成する Android Studioを開き、メニューの「File」→「New Project」を選択して、必要な項目を入力のうえ新しいプロジェクトを作成します。 手順2:activity_main.xmlにコードを追加する メイン画面のレイアウト

  2. 【Android】NavigationViewの実装方法をステップごとに解説

    この記事では、AndroidアプリでNavigationView(ナビゲーションビュー)を使用してドロワーメニューを実装する方法を、ステップごとに詳しく解説します。ハンバーガーアイコンから開閉できるサイドメニューは、多くのアプリで採用されている定番のUIです。ステップ1:新しいプロジェクトを作成するAndroid Studioを開き、File → New Project を選択して、必要な情報を入力し新しいプロジェクトを作成します。テンプレートには「Navigation Drawer Activity」を選ぶと、後の作業がスムーズになります。ステップ2:activity_main.xml にコ