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

Androidでアクティビティ間に値を渡す方法!StaticメソッドとIntentの2つの手法を解説

Androidアプリ開発では、画面(アクティビティ)間でデータを受け渡す場面が頻繁にあります。本記事では、データを永続化(保存)せずにアクティビティ間で値を渡す、最もシンプルな2つの方法——「Staticメソッドを使う方法」と「Intentを使う方法」——を、サンプルコード付きでステップごとに解説します。

方法1:Staticメソッドを使う

まずは、Staticメソッド(静的メソッド)を利用してアクティビティ間でデータを渡す方法を紹介します。Static変数はアプリ全体で共有されるため、別のアクティビティから直接参照できるのが特徴です。

ステップ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 に以下のコードを追加します。入力された文字列をStatic変数に格納し、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 {
   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);
         }
      });
   }
}

ステップ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 に以下のコードを追加します。MainActivityのStaticメソッド「getValue()」を呼び出して値を取得し、TextViewに表示します。

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 に以下のコードを追加します。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」Androidでアクティビティ間に値を渡す方法!StaticメソッドとIntentの2つの手法を解説アイコンをクリックします。実行デバイスとして自分のスマートフォンを選択すると、端末に初期画面が表示されます。

Androidでアクティビティ間に値を渡す方法!StaticメソッドとIntentの2つの手法を解説

方法2:Intentを使う(推奨)

続いて、Intent(インテント)を使ってアクティビティ間でデータを送受信する方法を紹介します。こちらがAndroidにおける標準的かつ推奨される手法です。Intentに「putExtra()」で値を格納し、受け取り側では「getExtras()」で取り出します。

ステップ1 − Android Studioで新しいプロジェクトを作成します。メニューから「File」→「New Project」を選択し、必要な情報を入力してプロジェクトを作成しましょう。

ステップ2 − res/layout/activity_main.xml に以下のコードを追加します。レイアウトは方法1と同じです。

<?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 に以下のコードを追加します。ポイントは「intent.putExtra()」で値をIntentに格納する部分です。

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 {
   @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();
            Intent intent = new Intent(MainActivity.this, SecondActivity.class);
            intent.putExtra("value", value);
            startActivity(intent);
         }
      });
   }
}

ステップ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 に以下のコードを追加します。「getExtras()」で受け取ったBundleから値を取り出し、nullチェックを行ってからTextViewに表示します。

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);
      Bundle bundle = getIntent().getExtras();
      if (bundle != null) {
         String value = bundle.getString("value");
         TextView textView = findViewById(R.id.text_view);
         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>

それではアプリを実行してみましょう。実機をパソコンに接続し、ツールバーの「Run」Androidでアクティビティ間に値を渡す方法!StaticメソッドとIntentの2つの手法を解説アイコンをクリックしてデバイスを選択します。EditTextに文字を入力して「Next」ボタンをタップすると、SecondActivityに入力した値が表示されます。

Androidでアクティビティ間に値を渡す方法!StaticメソッドとIntentの2つの手法を解説

2つの方法の使い分けのポイント

どちらの方法でもアクティビティ間のデータ受け渡しは可能ですが、それぞれ特徴が異なります。

  • Intent(putExtra):Androidの標準的な手法。ライフサイクルに沿った安全な受け渡しができ、型の異なる複数のデータも渡せます。特別な理由がない限り、こちらの使用を推奨します。
  • Staticメソッド:実装がシンプルな反面、Static変数はプロセスが生きている間メモリに残り続けるため、メモリリークや画面回転時の状態消失などのリスクがあります。あくまで簡易的な用途に留めましょう。

本記事のサンプルコードを参考に、自分のアプリに合った方法でデータ受け渡しを実装してみてください。

  1. Androidでアクティビティ間を画像を受け渡す方法をわかりやすく解説

    はじめに 本記事では、Androidアプリであるアクティビティ(Activity)から別のアクティビティへ画像を受け渡す方法を解説します。ここでは、Intentに画像のリソースIDを格納して渡す、最もシンプルで確実な手法を紹介します。 手順1:新規プロジェクトの作成 Android Studioで新しいプロジェクトを作成します。メニューから「File」→「New Project」を選択し、必要事項をすべて入力してプロジェクトを作成しましょう。 手順2:activity_main.xml の編集 res/layout/activity_main.xml に以下のコードを追加します。「Send

  2. 【Android】1つのフラグメントから別のフラグメントへデータを送信する方法(インターフェース活用の実装例)

    はじめに このチュートリアルでは、Androidアプリで1つのフラグメント(Fragment)から別のフラグメントへデータを送信する方法を解説します。フラグメント同士は直接通信することができません。そこで本記事では、カスタムインターフェース「SendMessage」を定義し、ホストとなるMainActivityを仲介してデータを受け渡す、定番かつ推奨されるパターンを紹介します。 具体的には、タブで切り替えられる2つのフラグメントを用意し、1つ目のフラグメントで入力したテキストをボタン操作で2つ目のフラグメントに表示させるサンプルアプリを作成します。 ステップ1:新しいプロジェクトを作成する