As I\'m learning Kotlin for Android development, I\'m now trying the basic programs like hello world and how to navigate from one activity to another activity , there is no
//On Click on Button
var but = findViewById<Button>(R.id.buttionActivity_two) as Button
but.setOnClickListener {
//Define intent
var intent = Intent(applicationContext,MainActivity::class.java)
// Here "first" is key and 123 is value
intent.putExtra("first",123)
startActivity(intent)
}
}
// If Get In Into Other Activity
var Intent1: Intent
Intent1= getIntent()
//Here first is key and 0 is default value
var obj :Int = Intent1.getIntExtra("first",0);
Log.d("mytag","VAlue is==>"+obj)
In Kotlin, you can pass the data simply by using the Intents. You can directly put your data in intent or you can write those data in bundle and send that bundle to another activity using the intent.
val intent = Intent(this@HomeActivity,ProfileActivity::class.java);
intent.putExtra("profileName", "John Doe")
var b = Bundle()
b.putBoolean("isActive", true)
intent.putExtras(b)
startActivity(intent);
Send value from HomeActivity
val intent = Intent(this@HomeActivity,ProfileActivity::class.java)
intent.putExtra("Username","John Doe")
startActivity(intent)
Get values in ProfileActivity
val profileName=intent.getStringExtra("Username")
You can just access the value without using extras or intent. Simply use companion object in MainActivity:
companion object{
val userName: String = String()
val password: String = String()
}
In SecondActivity:
var strUser: String = MainActivity.username
var strPassword: String = MainActivity.password
And you can access the values from multiple activities easily.
I'm on mobile, you must test by yourself.
Try to make a CharSequence
to a String
in MainActivity
, you have put a CharSequence
rather than a String
, for example:
var userName = username.text.toString()
var password = password_field.text.toString()
You can simply use the intents and bundle to send data from one activity to another activity.
val intent = Intent(this@OneActivity,TwoActivity::class.java);
intent.putExtra("username", userName)
startActivity(intent);