How to pass an object from one activity to another on Android
There are several ways you can pass an object from one activity to another on Android:
Using Intent Extras: You can put the object in the
Intent
that you use to start the second activity. To do this, you need to make the objectParcelable
orSerializable
, then use theputExtra
method of theIntent
class to pass the object.Using a Singleton: You can use a singleton class to store the object, and then retrieve it from the second activity.
Using a Static Field: You can create a static field in your first activity and set it to the object you want to pass. The second activity can then access the static field to retrieve the object.
Using a Shared ViewModel: If you are using the Android Architecture Components library, you can use a
ViewModel
to store the object and pass it between activities.Using a Database: If the object you want to pass is large or you want to persist it, you can store it in a database and pass the object's ID to the second activity. The second activity can then query the database to retrieve the object.