My main activity code is here
class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val button=findViewById<Button>(R.id.save) val loadButton=findViewById<Button>(R.id.load) loadButton.setOnClickListener { findViewById<EditText>(R.id.username).text } button.setOnClickListener { startActivity(Intent(this,DisplayActivity::class.java). putExtra("username",findViewById<TextView>(R.id.username).text)) } } }
class DisplayActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_display) val username=intent.getStringExtra("username").toString(); findViewById<TextView>(R.id.username1).text=username; } }
but when I click the Save Button(R.id.save) the textview is being displayed as null. Where am I going wrong?
Using only mEditText.text
returns the Editable
not String
, try below code:
//...
// Rest of the code above
val loadButton = findViewById<Button>(R.id.load)
val mEditText = findViewById<EditText>(R.id.username)
loadButton.setOnClickListener {
startActivity(Intent(this, DisplayActivity::class.java).apply {
putExtra("username", mEditText.text.toString()) // <- toString()
})
}
And get the value like this:
class DisplayActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_display)
val username = intent.getStringExtra("username")
findViewById<TextView>(R.id.username1).text = username
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.