Passing Data/Message

Passing Data/Message

Pass Data/Message Between Activities With Intent

By Using Instance of Intent we can Pass data from one activity to another
Intent.putExtra() function take data as arguments with String Key
 
  • While There Many functions are there to Get data from Intent to get data sent by intent You must which Type of Data are getting sent from activity then use function of this Data type to get Data
  • like:
    • For Int you need to use intent.getIntExtra( key-name )
    • For String you need to use intent.getStringExtra( key-name )
    • For Double you need to use intent.getDoubleExtra( key-name )
    • For Boolean you need to use intent.getBooleanExtra( key-name )

Example:

  • Pass data while going to second activity
val intent = Intent(this@MainActivity,SecondActivity::class.java) intent.putExtra("name","Devansh") intent.putExtra("age",20) intent.putExtra("country","India") startActivity(intent)
  • on second activity to get data
val name = intent.getStringExtra("name") val age = intent.getIntExtra("age",0) val country = intent.getStringExtra("country")

- Another way to pass Data with help of Data Class in kotlin

  • In This Method You need data class with member to store value to pass with instances of that class
  • this Data class must be Inherited from Serializable class to pass with intent
data class Person( val name: String, val age : Int, val country : String ) : Serializable
  • from MainActivity write code to pass intent
Intent(this@MainActivity,SecondActivity::class.java).also { val person1 = Person("Devansh",20 , "India") it.putExtra("p1",person1) startActivity(it) }
  • In SecondActivity write code to get data from instances of class
    • You must need to convert into Person object Otherwise it cannot be usable
val person = intent.getSerializableExtra("p1") as Person