Androidのアクティビティ間でデータを受け渡す方法|静的メソッドとIntent
このレッスンでは、データを永続化(保存)せずにアクティビティ間でデータを受け渡す方法に焦点を当てます。その中でも最もシンプルな2つの手法である「静的(Static)メソッド」と「Intent」を使ったアプローチを紹介します。
静的(Static)メソッドを使う方法
ここでは、静的メソッドを利用してAndroidのアクティビティ間でデータを受け渡すサンプルを解説します。仕組みはシンプルで、MainActivity側のstaticフィールドに入力値を保持し、遷移先の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>
このレイアウトには、テキスト入力用のEditTextと、次の画面へ遷移するためのButtonを縦方向に配置しています。
ステップ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);
}
});
}
}
ボタンがクリックされると、EditTextの入力内容を前後の空白を除去したうえで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());
}
}
onCreate()内でMainActivity.getValue()を呼び出し、受け取った文字列をTextViewにセットしています。
ステップ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>
マニフェストにはSecondActivityの宣言を忘れずに追加してください。宣言がないと、画面遷移時にアプリがクラッシュします。
アプリの実行と動作確認
それでは、アプリケーションを実行してみましょう。実際のAndroid端末をパソコンに接続しているものとして説明を進めます。Android Studioからアプリを実行するには、プロジェクト内のいずれかのアクティビティファイルを開き、ツールバーにある実行アイコン
をクリックします。デバイス選択のダイアログで自分のモバイル端末を選択すると、端末に以下のような初期画面が表示されます。

テキストボックスに任意の文字列を入力して「Next」ボタンをタップすると、次の画面に入力した内容が表示されるはずです。
静的メソッドを使う際の注意点
staticフィールドはアプリのプロセスが生存している間しか値を保持できません。システムによってプロセスが強制終了された場合や、メモリ不足でアクティビティが再生成された場合には、値が失われる可能性があります。そのため、この手法は学習用・簡易的な用途に向いており、本番アプリではIntentのエクストラ(putExtra())やViewModel、SharedPreferencesなど、目的に応じた適切な手段を選ぶことをおすすめします。
-
Androidでモバイルデータ通信をプログラムから無効化する方法
この記事では、Androidアプリからモバイルデータ通信を有効・無効に切り替える方法を解説します。 はじめに知っておくべき重要な制限 まず押さえておきたい点として、ルート化されていない端末では、プログラムによるモバイルデータのオン/オフは基本的にできません。これは、データ通信の制御には MODIFY_PHONE_STATE 権限が必要ですが、この権限はシステムアプリまたは署名済みアプリにしか付与されないためです。 また、かつてリフレクション経由で呼び出せた setMobileDataEnabled() メソッドにも注意が必要です。このメソッドは Android 2.1(API 7)〜 Andr
-
Androidのデータバインディング入門:Data Binding Libraryでレイアウトとデータを結びつける方法
データバインディングとは、アプリが扱う「データ」と、画面上の視覚的なUI要素を結びつける(バインドする)ための手法です。この仕組みを使うと、UI側の値が更新されるたびに、裏側で保持しているデータも自動的に更新されます。 決して目新しい概念ではなく、AngularJS、React、Vueなど、多くのフロントエンドフレームワークがすでにこの仕組みを設計に取り入れています。 しかし本記事で注目するのはフロントエンドフレームワークではなく、モバイル開発です。GoogleはAndroid向けにData Binding Libraryを提供しており、これはAndroid Jetpackの一部として位置づけ