Issue
How to make an Edit Text on a screen so that when we press the send button it will display the message typed by user on next screen inside a text view.
I tried the following code but it gives an error message as unresolved reference: intent2.
- I created two activities and named them as MainActivity.kt and MessageActivity.kt and their respective layout files as activity_main.xml and activity_message.xml .
2.Inside the activity_main.xml file I made an EditText view whose id is etMessage is and a button below it called send whose id is btnSend. This button must take the message entered by the user in the message box and send it to the next screen inside a textview of activity_message.xml whose id is txtEmpty and display the message in it.
so here's the code from MainActivity.kt
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
class MainActivity : AppCompatActivity() {
lateinit var etMessage: EditText
lateinit var btnSend: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
etMessage=findViewById(R.id.etMessage)
btnSend=findViewById(R.id.btnSend)
val intent2= Intent(this@MainActivity,MessageActivity::class.java)
btnSend.setOnClickListener(){
var message= etMessage.text.toString()
intent2.putExtra("Message",message)
startActivity(intent2)
}
}
}
and the code in MessageActivity.kt is..
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
class MessageActivity : AppCompatActivity() {
lateinit var txtEmpty: TextView
var txtMessage:String?="Message"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_message)
txtEmpty= findViewById(R.id.txtEmpty)
if(intent2!=null){
txtMessage=intent2.getStringExtra("Message")
}
txtEmpty.text=txtMessage
}
}
When I try to launch the app it's giving an error. Can someone please explain what's wrong with my code and what's the correct way of doing this?
Solution
Actually intent2 is the name of your variable in MainActivity. There is no variable named intent2 in MessageActivity.
You can reach text like this
txtMessage = intent.getStringExtra("Message")
Answered By - Melih Yaşar SÖZEN
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.