【Android開発】IntentとBundleを使ってアクティビティ間で複数のデータを渡す方法を解説
このチュートリアルでは、Androidアプリ開発において、IntentとBundleを使用して、あるアクティビティ(Activity)から別のアクティビティへ複数のデータを渡す方法を、実際のコード例とともにステップごとに解説します。
データの受け渡しには「Bundle」という仕組みを使います。Bundleはキーと値のペアで複数のデータをまとめて管理でき、Intentに格納して次の画面へ引き継ぐことができます。名前や年齢など、複数項目を一度に送りたい場合に非常に便利です。
ステップ1:新しいプロジェクトを作成する
Android Studioを開き、「File」→「New Project」を選択して、必要な情報を入力し、新しいプロジェクトを作成します。
ステップ2:メイン画面のレイアウトを作成する(activity_main.xml)
res/layout/activity_main.xml に以下のコードを追加します。名前入力用と年齢入力用の2つの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/etName" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:layout_gravity = "center" android:hint = "Name" android:inputType = "text" /> <EditText android:id = "@+id/etAge" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:layout_gravity = "center" android:hint = "Age" android:inputType = "number" /> <Button android:id = "@+id/button" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:layout_gravity = "center" android:layout_marginTop = "16dp" android:text = "Next" /> </LinearLayout>
ステップ3:MainActivity.javaにデータ送信処理を実装する
src/MainActivity.java に以下のコードを追加します。ボタンがクリックされたときに入力内容を取得し、Bundleに格納してからIntentにセットし、SecondActivityを起動します。
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 {
EditText etName, etAge;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etName = findViewById(R.id.etName);
etAge = findViewById(R.id.etAge);
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String name = etName.getText().toString().trim();
String age = etAge.getText().toString().trim();
Bundle bundle = new Bundle();
bundle.putString("name", name);
bundle.putString("age", age);
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtras(bundle);
startActivity(intent);
}
});
}
}ポイントは bundle.putString() でキー名(ここでは「name」「age」)を指定してデータを保存し、intent.putExtras(bundle) でIntentにまとめて渡している点です。このキー名は受け取り側でも同じものを使用します。
ステップ4:2つ目の画面レイアウトを作成する(activity_second.xml)
res/layout/activity_second.xml に以下のコードを追加します。受け取った名前と年齢を表示するためのTextViewを2つ配置しています。
<?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/tvName" android:layout_width = "match_parent" android:layout_height = "wrap_content" /> <TextView android:id = "@+id/tvAge" android:layout_width = "match_parent" android:layout_height = "wrap_content" /> </LinearLayout>
ステップ5:SecondActivity.javaでデータを受け取る処理を実装する
src/SecondActivity.java に以下のコードを追加します。getIntent().getExtras() でBundleを取得し、キー名を指定して各データを取り出してTextViewに表示します。
package com.example.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class SecondActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
String name = bundle.getString("name");
String age = bundle.getString("age");
TextView tvName = findViewById(R.id.tvName);
TextView tvAge = findViewById(R.id.tvAge);
tvName.setText(name);
tvAge.setText(age);
}
}
}nullチェックを行うことで、Extrasが存在しない場合のクラッシュ(NullPointerException)を防いでいます。安全な実装のためにも必ず入れておきましょう。
ステップ6:AndroidManifest.xmlにアクティビティを登録する
androidManifest.xml に以下のコードを追加します。SecondActivityも忘れずにマニフェストへ宣言してください。
<?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
」アイコンをクリックします。デバイスを選択すると、モバイル端末に初期画面が表示されます。

名前と年齢を入力して「Next」ボタンをタップすれば、SecondActivityへ遷移し、入力した複数のデータが正しく引き継がれて表示されることが確認できます。
まとめ
このように、Bundle + Intent + putExtras() の組み合わせを使えば、文字列だけでなく数値や真偽値など、さまざまな型の複数データをアクティビティ間で簡単に受け渡すことができます。画面遷移時のデータ共有はAndroidアプリ開発の基本テクニックなので、ぜひマスターしておきましょう。
-
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:新しいプロジェクトを作成する