package com.example.passingdata
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class MessageSender : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_message_sender)
val editTextMessage = findViewById<EditText>(R.id.editTextMessage)
val buttonSend = findViewById<Button>(R.id.buttonSend)
buttonSend.setOnClickListener {
val message = editTextMessage.text.toString()
val intent = Intent(this, MessageReceiver::class.java)
intent.putExtra("EXTRA_MESSAGE", message)
startActivity(intent)
}
}
}
class MessageReceiver : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_message_receiver)
val textViewReceived = findViewById<TextView>(R.id.textViewReceived)
val message = intent.getStringExtra("EXTRA_MESSAGE") ?: "No message received"
textViewReceived.text = message
}
}We added a click listener to the Send button in MessageSender. When clicked, it reads the text from the EditText, creates an Intent to start MessageReceiver, and puts the message as an extra with key "EXTRA_MESSAGE". Then it starts the new activity.
In MessageReceiver, we get the Intent that started it and read the string extra with the same key. We show this message in a TextView. This way, data passes from one screen to another simply and clearly.