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

【Android】IntentとBundleを使ってアクティビティ間でデータを受け渡す方法

はじめに

このチュートリアルでは、Androidアプリケーションにおいてアクティビティ(Activity)間でデータを受け渡す方法を解説します。IntentBundleを活用し、名前と年齢層の入力値を別の画面に渡してメッセージを表示する、シンプルなサンプルアプリを一緒に作っていきましょう。

手順1:新規プロジェクトの作成

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

手順2:レイアウトファイル(activity_first.xml)の作成

res/layout/activity_first.xml に以下のコードを追加します。名前を入力するEditText、年齢層を選択するSpinner、送信用のButtonを配置しています。

<?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"
    android:id="@+id/activity_first"
    android:paddingTop="60dp"
    tools:context=".FirstActivity">
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:paddingLeft="10sp">
            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="0.25"/>
            <EditText
                android:id="@+id/editTxtName"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="0.75"
                android:ems="10" />
        </LinearLayout>
        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:paddingLeft="10sp"
            android:paddingTop="16dp">
            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="0.25" />
            <Spinner
                android:id="@+id/ageGroupSpinner"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:layout_weight="0.75"/>
        </LinearLayout>
        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:paddingTop="16dp">
            <View
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="0.50" />
            <Button
                android:id="@+id/btnSubmit"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="0.20"/>
        </LinearLayout>
    </LinearLayout>
</RelativeLayout>

手順3:レイアウトファイル(activity_second.xml)の作成

res/layout/activity_second.xml に以下のコードを追加します。受け取ったデータを表示するためのTextViewを配置しています。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/activity_second"
    android:paddingTop="60dp">
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:paddingLeft="10sp">
            <TextView
                android:id="@+id/displayMsg"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="0.25" />
        </LinearLayout>
    </LinearLayout>
</RelativeLayout>

手順4:FirstActivity.java の実装

src/FirstActivity.java に以下のコードを追加します。「送信」ボタンがタップされると、まず名前の入力チェックを行い、問題がなければ名前と年齢層をBundleに格納し、IntentにセットしてSecondActivityへ遷移します。

package com.example.sample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class FirstActivity extends AppCompatActivity {
    Button btnSubmit = null;
    EditText editTxtName = null;
    private static final String STING_EMPTY = "";
    private static int ageGroup = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first);
        btnSubmit = (Button) findViewById(R.id.btnSubmit);
        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                editTxtName = (EditText) findViewById(R.id.editTxtName);
                if (STING_EMPTY.equals(editTxtName.getText().toString())) {
                    Toast.makeText(FirstActivity.this, "Name Cannot be empty!",
                    Toast.LENGTH_LONG).show();
                } else {
                    Spinner ageGroupSpinner = (Spinner)findViewById(R.id.ageGroupSpinner);
                    ageGroupSpinner.setOnItemSelectedListener(
                    new AdapterView.OnItemSelectedListener() {
                        @Override
                        public void onItemSelected(AdapterView<?> adapterView, View view,
                        int i, long l) {
                            //set the corresponding age group when the user changes
                            // the age group from dropdown
                            ageGroup = i;
                        }
                        @Override
                        public void onNothingSelected(AdapterView<?> adapterView) {
                        }
                    });
                    //Create a new intent for the SecondActivity
                    Intent i = new Intent(FirstActivity.this,SecondActivity.class);
                    //Populate the input values in a bundle and pass it to SecondActivity
                    Bundle b = new Bundle();
                    b.putString("name",editTxtName.getText().toString());
                    b.putInt("ageGroup",ageGroup);
                    //Set the userBundle to the intent
                    i.putExtra("userBundle",b);
                    startActivity(i);
                }
            }
        });
    }
}

手順5:SecondActivity.java の実装

src/SecondActivity.java に以下のコードを追加します。受け取ったIntentからBundleを取り出し、名前と年齢層に応じたメッセージを組み立ててTextViewに表示します。

package com.example.sample;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class SecondActivity extends AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        //get the passed intent
        Intent i = getIntent();
        //get the bundle stored inside the intent
        Bundle b = i.getBundleExtra("userBundle");
        TextView displayMsg = (TextView) findViewById(R.id.displayMsg);
        String message = "Hi, " + b.getString("name") + " ";
        int ageGroup = b.getInt("ageGroup");
        switch (ageGroup){
            case 0: message = message + "Enjoy your life";
            break;
            case 1: message = message + "Don't take life too seriously.. Have fun!";
            break;
            case 2: message = message + "Celebrate your life with old memories!";
            break;
        }
        displayMsg.setText(message);
    }
}

手順6:AndroidManifest.xml の編集

Manifests/AndroidManifest.xml に以下のコードを追加します。新しいアクティビティを作成したら、必ずマニフェストファイルにも登録する必要がある点に注意しましょう。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.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=".FirstActivity">
            <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】IntentとBundleを使ってアクティビティ間でデータを受け渡す方法

【Android】IntentとBundleを使ってアクティビティ間でデータを受け渡す方法

まとめ

このように、IntentにBundleをセットすることで、複数のデータをひとまとめにして次のアクティビティへ渡すことができます。putExtra()で個別に値を渡す方法もありますが、Bundleを使えば関連するデータを一括して管理でき、コードの可読性や保守性が向上します。ぜひご自身のアプリ開発にも役立ててください。

  1. 【Android】プログラムでアプリケーションを終了する方法|finish()とSystem.exit(0)の使い方

    はじめにこの記事では、Androidアプリをプログラム(コード)から終了させる方法を解説します。ボタンをタップするとアプリが終了するシンプルなサンプルアプリを通じて、実装手順をステップごとに見ていきましょう。ステップ1:新規プロジェクトの作成Android Studioを起動し、「File」→「New Project」を選択します。必要な項目をすべて入力して、新しいプロジェクトを作成してください。ステップ2:レイアウトファイルの編集res/layout/activity_main.xml に以下のコードを追加します。このレイアウトには、ガイダンス用のTextViewと、アプリを終了するためのB

  2. Androidのデータバインディング入門:Data Binding Libraryでレイアウトとデータを結びつける方法

    データバインディングとは、アプリが扱う「データ」と、画面上の視覚的なUI要素を結びつける(バインドする)ための手法です。この仕組みを使うと、UI側の値が更新されるたびに、裏側で保持しているデータも自動的に更新されます。 決して目新しい概念ではなく、AngularJS、React、Vueなど、多くのフロントエンドフレームワークがすでにこの仕組みを設計に取り入れています。 しかし本記事で注目するのはフロントエンドフレームワークではなく、モバイル開発です。GoogleはAndroid向けにData Binding Libraryを提供しており、これはAndroid Jetpackの一部として位置づけ