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

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

このチュートリアルでは、Kotlinを使ってAndroidアプリのアクティビティ間でデータを受け渡す方法を解説します。BundleSerializableを活用することで、名前や電話番号といったユーザー情報をオブジェクトごと次の画面へ簡単に渡すことができます。

ステップ1:新規プロジェクトの作成

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

ステップ2:レイアウトファイル(activity_main.xml)の作成

res/layout/activity_main.xmlに以下のコードを追加します。名前と電話番号を入力するためのEditTextが2つと、データを送信する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_centerHorizontal="true"
    android:orientation="vertical"
    android:padding="4dp"
    tools:context=".MainActivity">
    <EditText
        android:id="@+id/etName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Enter a name"
        android:inputType="text" />
    <EditText
        android:id="@+id/etPhone"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Enter a Phone number"
        android:inputType="number" />
    <Button
        android:id="@+id/btnSend"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Send data" />
</LinearLayout>

ステップ3:MainActivity.ktの実装

src/MainActivity.ktに以下のコードを追加します。ボタン押下時に入力値の空チェックを行い、問題がなければUserInfoオブジェクトにデータを格納し、BundleにシリアライズしてSecondActivityへ渡します。

import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import java.io.Serializable
class MainActivity : AppCompatActivity() {
    lateinit var etName: EditText
    lateinit var etPhone: EditText
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"
        etName = findViewById(R.id.etName)
        etPhone = findViewById(R.id.etPhone)
        val btnSend: Button = findViewById(R.id.btnSend)
        btnSend.setOnClickListener {
            if (TextUtils.isEmpty(etName.text.toString()) && TextUtils.isEmpty(etPhone.text.toString())) {
                Toast.makeText(this, "Something is wrong kindly check", Toast.LENGTH_LONG).show()
            }
            else {
                sendUserData(etName.text.toString(), etPhone.text.toString())
            }
        }
    }
    private fun sendUserData(username: String, userPhone: String) {
        val userInfo = UserInfo()
        userInfo.setName(username)
        userInfo.setPhone(userPhone)
        val send = Intent(this@MainActivity, SecondActivity::class.java)
        val b = Bundle()
        b.putSerializable("serialzable", userInfo)
        send.putExtras(b)
        startActivity(send)
    }
}
class UserInfo : Serializable {
    private lateinit var name: String
    private lateinit var phone: String
    fun getName(): String? {
        return name
    }
    @JvmName("setName1")
    fun setName(name: String?) {
        this.name = name!!
    }
    fun getPhone(): String? {
        return phone
    }
    @JvmName("setPhone1")
    fun setPhone(phone: String?) {
        this.phone = phone!!
    }
}

ステップ4:SecondActivityの作成

新しい空のアクティビティを作成し、以下のコードを追加します。

activity_second.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:padding="4dp"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="70dp"
        android:background="#008080"
        android:padding="5dp"
        android:text="TutorialsPoint"
        android:textColor="#fff"
        android:textSize="24sp"
        android:textStyle="bold" />
    <TextView
        android:textAlignment="center"
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:textColor="@android:color/holo_purple"
        android:textSize="24sp"
        android:textStyle="bold" />
</RelativeLayout>

SecondActivity.kt

受け取ったIntentからSerializableなExtraを取り出し、TextViewに入力内容を表示します。onPause()で参照を解放している点にも注目してください。

import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class SecondActivity : AppCompatActivity() {
    private var userInfo: UserInfo? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_second)
        title = "KotlinApp"
        val tvData: TextView = findViewById(R.id.textView)
        userInfo = intent.getSerializableExtra("serialzable") as UserInfo?
        val name: String = userInfo?.getName().toString()
        val phone: String = userInfo?.getPhone().toString()
        tvData.text = "Your entered name is $name number is $phone"
    }
    override fun onPause() {
        super.onPause()
        userInfo = null
    }
}

ステップ5:AndroidManifest.xmlの編集

androidManifest.xmlに以下のコードを追加します。起動用アクティビティとしてMainActivityが登録されていることを確認しましょう。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.example.q11">
    <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>
    </application>
</manifest>

アプリを実行してみよう

それでは、アプリケーションを実行してみましょう。ここでは、実際のAndroid端末がパソコンに接続されていることを前提としています。Android Studioからアプリを実行するには、プロジェクト内のアクティビティファイルを開き、ツールバーの実行アイコン【Kotlin】Bundleを使ってAndroidのアクティビティ間でデータを受け渡す方法をクリックします。デバイス選択の選択肢から自分のモバイルデバイスを選ぶと、端末にアプリの初期画面が表示されます。

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

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

  1. 【Android開発】SharedPreferencesを使ってアクティビティ間でデータを受け渡す方法を解説

    Androidアプリ開発では、ある画面(アクティビティ)から別の画面へデータを受け渡したい場面が多くあります。一般的には Intent のエクストラを使う方法が定番ですが、本記事では SharedPreferences(共有プリファレンス) を利用してデータを渡す方法を、ステップごとのサンプルコード付きでわかりやすく解説します。 SharedPreferencesとは? SharedPreferencesは、キーと値のペア形式で少量のデータを永続的に保存できる仕組みです。通常は設定情報の保存に使われますが、この仕組みを応用すると、異なるアクティビティ間で同じストレージを読み書きすることで、デ

  2. Androidでアクティビティ間にドローアブルを渡す方法【サンプルコード付きで解説】

    この記事では、Androidアプリにおいて2つのアクティビティ間でドローアブル(画像リソース)を受け渡す方法を、実際に動作するサンプルコードとともに段階的に解説します。実装のポイント:ドローアブル本体ではなく「リソースID」を渡すドローアブルオブジェクトをIntentに直接渡そうとすると、データサイズが大きすぎてエラーになる場合があります。そこで本記事では、ドローアブルのリソースID(int値)を putExtra() で渡し、受け取り側で setImageResource() を使って表示するというシンプルかつ確実な手法を採用します。これが画像リソースの受け渡しにおけるベストプラクティスです