Reputation: 103
I'm trying to create simple app where you type your data in one activity by editText and it's shown in another in TextView. But i really don't know how to make it work. As you can see this is simple code but right now when i click submit nothing happens on another activity. this is first activty
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
fun switchToActivity (view: View){
val myIntent = Intent(this, Main2Activity::class.java)
startActivity(myIntent)
}
override fun onActivityResult(requestCode: Int,
resultCode: Int,
myInten: Intent?) {
var text2 = myInten?.getStringExtra("text")
textView.setText(text2)
}
}
And this is second
class Main2Activity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main2)
}
fun buttonListener (view: View){
var text = editText.text.toString()
val myIntent = Intent()
myIntent.putExtra("textView", text)
setResult(Activity.RESULT_OK, myIntent)
finish()
}
}
Upvotes: 0
Views: 72
Reputation: 14173
There are 2 issues with your code.
First, to receive result from another activity, you must use startActivityForResult() instead.
fun switchToActivity (view: View){
val myIntent = Intent(this, Main2Activity::class.java)
startActivityForResult(myIntent)
}
Second, you must use the same key when saving and retrieving result.
var text2 = myInten?.getStringExtra("textView")
Put it together.
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
fun switchToActivity (view: View){
val myIntent = Intent(this, Main2Activity::class.java)
startActivityForResult(myIntent)
}
override fun onActivityResult(requestCode: Int,
resultCode: Int,
myInten: Intent?) {
var text2 = myInten?.getStringExtra("textView")
textView.setText(text2)
}
}
Upvotes: 2
Reputation: 592
You should use: startActivityForResult(myIntent)
instead of: startActivity(myIntent)
Upvotes: 0