As far as I understand, you are looking for extra
.
When starting one Activity
from another, you can pass data via extra
.
Let's say you have a class Person
with String name
and int age
.
There are 2 simple ways to to this.
1. Send data separately
Because Person
is a simple class that consists of 2 member fields, we can pass each data separately and combine into Person
in started Activity
.
We need Intent
to do this.
val p = Person(name, age) // Person data
val intent = Intent(this, NewActivity::class.java)
intent.putExtra('name', p.name)
intent.putExtra('age', p.age)
startActivity(intent)
On started NewActivity
's onCreate()
, you can receive this data and make an object out of it.
val name = intent.getStringExtra('name')
val age = intent.getIntExtra('age')
val combinedPersonData = Person(name, age)
2. Send whole instance
If the class you are trying to send is too big to use method 1, you can try sending it as itself.
To do this, you need to implement Serializable
or Parcelable
to your class.
class Person(val name: String, val age: Int): Serializable { ... }
Make sure all of the members in the class are also Serializable or are primitive types.
With this, you can send the person object as serializable object.
val p = Person(name, age) // Person data
val intent = Intent(this, NewActivity::class.java)
intent.putExtra('person', p)
startActivity(intent)
In the receiver's onCreate()
,
val p = intent.getSerializableExtra('person') as Person
will receive the while Person
data.