class FirstActivity : AppCompatActivity() {
companion object{
val USER_KEY="FirstActivity"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_first)
button_firstActivity.setOnClickListener {
val string:String=textView_first.text.toString()
val intent=Intent(this,MainActivity::class.java)
intent.putExtra(USER_KEY,string)
startActivity(intent)
}
}
}
class MainActivity : AppCompatActivity() {
companion object{
val MAINUSERKEY="MainActivity"
var str:String=""
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
str=intent.getStringExtra(FirstActivity.USER_KEY)
textview_main.text=str
button_Run.setOnClickListener {
val edittextstring=editText1.text.toString()
val intent=Intent(this,MainActivity::class.java)
intent.putExtra(MAINUSERKEY,edittextstring)
startActivity(intent)
}
}
}
Hello every one! I am new to Android programming with Kotlin.
I have two activities, suppose A and B. I want to start activity B from A and when B starts, it will display the TextView
string of A into TextView_Main
.
It is working fine now. I want to start activity B again on clicking button_Run
which is on Activity B and passing a string again which I entered in edittext
of Activity B. And now it should be displayed on textview
of Activity B, when it opens again.
Please help me do this.
The problem is that the edittext
string is being stored as an intent extra with name MAINUSERKEY="MainActivity”
, which is different from the extra you are currently extracting on your MainActivity
, the one with name USER_KEY="FirstActivity”
. So I would do something like this to ensure I get the correct string extra:
str = with(intent) {
getStringExtra(FirstActivity.USER_KEY) ?: getStringExtra(MainActivity.MAINUSERKEY) ?: "No string extra was found"
}