0

I followed this guide (How to run a certain activity in Android Studio?) to launch another activity aside from my main.

I have a GetUser.xml and ShowUser.xml layouts. In GetUser.xml, user can enter their name and age.

I have a user class with constructor that takes in name and age inside GetUser.kt. I initialize User object with the values : name, age I got from the input fields in GetUser.

Now when I run the other activity ShowUser, I wish to access this object so I can get the values and display it in ShowUser.xml

My question is how do I access this object from the GetUser.kt and use it in ShowUser.kt ?

Zoe
  • 27,060
  • 21
  • 118
  • 148
Abeart
  • 21
  • 3
  • (1) Send the data as `Intent` from GetUser to ShowUser activity. (2) Store data as `SharedPreferences`. (3) Ugly solution: Create a global object holding the data as properties. – Michael Butscher Nov 03 '18 at 02:16

1 Answers1

0

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.

Hyun I Kim
  • 589
  • 1
  • 3
  • 14