【Android】Intentを使わずにアクティビティ間でデータを受け渡す方法
はじめに
Androidアプリ開発では、通常IntentのExtrasを利用してアクティビティ間でデータを受け渡します。しかし、単純な値の共有であれば、Intentに頼らずに済ませることも可能です。この記事では、static変数を使う方法とSharedPreferencesを使う方法という2つのアプローチを、サンプルコードとともにステップごとに解説します。
方法1:static変数を使う方法
この例では、MainActivityにstaticなフィールド変数とgetterメソッドを用意し、SecondActivityから直接参照することでデータを受け渡します。
ステップ1:新規プロジェクトを作成する
Android Studioで「File」→「New Project」を選択し、必要な情報を入力して新しいプロジェクトを作成します。
ステップ2:res/layout/activity_main.xml に以下のコードを追加する
<?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:src/MainActivity.java に以下のコードを追加する
package com.example.myapplication;
import android.content.Intent;
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 {
private static String value;
public static String getValue() {
return value;
}
@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) {
value = editText.getText().toString().trim();
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
}
});
}
}
ここでは、入力された文字列をstatic変数 value に格納しています。Intentには何も渡さず、単にSecondActivityを起動するだけである点に注目してください。
ステップ4:res/layout/activity_second.xml に以下のコードを追加する
<?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:src/SecondActivity.java に以下のコードを追加する
package com.example.myapplication;
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);
textView.setText(MainActivity.getValue());
}
}
ステップ6:AndroidManifest.xml に以下のコードを追加する
<?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端末がPCに接続されているものとします。Android Studioから実行するには、プロジェクト内の任意のアクティビティファイルを開き、ツールバーのRunアイコンをクリックします。デバイス選択画面でお使いのモバイル端末を選択すると、端末に次のような初期画面が表示されます。

テキストフィールドに文字を入力して「Next」ボタンをタップすると、入力内容がSecondActivity側に表示されます。
方法2:SharedPreferencesを使う方法
続いて、SharedPreferencesを使ってアクティビティ間でデータを送受信する例を紹介します。キーと値のペアとしてデータを保存するため、小規模な設定値や状態の保持に適した手法です。
ステップ1:新規プロジェクトを作成する
Android Studioで「File」→「New Project」を選択し、必要な情報を入力して新しいプロジェクトを作成します。
ステップ2:res/layout/activity_main.xml に以下のコードを追加する
<?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:src/MainActivity.java に以下のコードを追加する
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);
}
});
}
}
ボタンが押されたタイミングで、入力された文字列を「myKey」という名前のSharedPreferencesに「value」というキーで保存しています。
ステップ4:res/layout/activity_second.xml に以下のコードを追加する
<?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:src/SecondActivity.java に以下のコードを追加する
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 に以下のコードを追加する
<?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端末をPCに接続したうえで、Android StudioのツールバーにあるRunアイコンをクリックしてアプリを起動します。デバイス一覧からお使いのモバイル端末を選択すると、端末に初期画面が表示され、入力した内容がSecondActivityに引き継がれていることを確認できます。

まとめ:2つの手法の違いと使い分け
static変数による方法は実装が非常にシンプルな反面、アプリのプロセスが破棄されるとデータが失われるほか、Activityのライフサイクルやメモリ管理との相性にも注意が必要です。一方、SharedPreferencesはデータがディスク上に永続化されるため、アプリを再起動しても値を保持でき、より堅牢な設計になります。一時的な受け渡しならstatic変数、後から参照する可能性のあるデータならSharedPreferencesといった具合に、用途に応じて使い分けるのがおすすめです。
なお、本記事のサンプルコードは旧サポートライブラリ(android.support)を使用していますが、最新のAndroid StudioではAndroidX(androidx.appcompat.app.AppCompatActivity)への移行が推奨されています。新規プロジェクトで試す場合は、適宜読み替えてください。
-
Androidでアクティビティ間を画像を受け渡す方法をわかりやすく解説
はじめに 本記事では、Androidアプリであるアクティビティ(Activity)から別のアクティビティへ画像を受け渡す方法を解説します。ここでは、Intentに画像のリソースIDを格納して渡す、最もシンプルで確実な手法を紹介します。 手順1:新規プロジェクトの作成 Android Studioで新しいプロジェクトを作成します。メニューから「File」→「New Project」を選択し、必要事項をすべて入力してプロジェクトを作成しましょう。 手順2:activity_main.xml の編集 res/layout/activity_main.xml に以下のコードを追加します。「Send
-
【Android】1つのフラグメントから別のフラグメントへデータを送信する方法(インターフェース活用の実装例)
はじめに このチュートリアルでは、Androidアプリで1つのフラグメント(Fragment)から別のフラグメントへデータを送信する方法を解説します。フラグメント同士は直接通信することができません。そこで本記事では、カスタムインターフェース「SendMessage」を定義し、ホストとなるMainActivityを仲介してデータを受け渡す、定番かつ推奨されるパターンを紹介します。 具体的には、タブで切り替えられる2つのフラグメントを用意し、1つ目のフラグメントで入力したテキストをボタン操作で2つ目のフラグメントに表示させるサンプルアプリを作成します。 ステップ1:新しいプロジェクトを作成する