How to pass an object from one activity to another on Android
Implement your class with Serializable. Let's suppose that this is your entity class:
import java.io.Serializable;
@SuppressWarnings("serial") //With this annotation we are going to hide compiler warnings
public class Deneme implements Serializable {
public Deneme(double id, String name) {
this.id = id;
this.name = name;
}
public double getId() {
return id;
}
public void setId(double id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
private double id;
private String name;
}
We are sending the object called dene
from X activity to Y activity. Somewhere in X activity;
Deneme dene = new Deneme(4,"Mustafa");
Intent i = new Intent(this, Y.class);
i.putExtra("sampleObject", dene);
startActivity(i);
In Y activity we are getting the object.
Intent i = getIntent();
Deneme dene = (Deneme)i.getSerializableExtra("sampleObject");
That's it.
One option could be letting your custom class implement the Serializable
interface and then you can pass object instances in the intent extra using the putExtra(Serializable..)
variant of the Intent#putExtra()
method.
Actual Code:
In Your Custom Model/Object Class:
public class YourClass implements Serializable {
At other class where using the Custom Model/Class:
//To pass:
intent.putExtra("KEY_NAME", myObject);
myObject is of type "YourClass". Then to retrieve from another activity, use getSerializableExtra get the object using same Key name. And typecast to YourClass is needed:
// To retrieve object in second Activity
myObject = (YourClass) getIntent().getSerializableExtra("KEY_NAME");
Note: Make sure each nested class of your main custom class has implemented Serializable interface to avoid any serialization exceptions. For example:
class MainClass implements Serializable {
public MainClass() {}
public static class ChildClass implements Serializable {
public ChildClass() {}
}
}
Use gson to convert your object to JSON and pass it through intent. In the new Activity convert the JSON to an object.
In your build.gradle
, add this to your dependencies
implementation 'com.google.code.gson:gson:2.8.4'
In your Activity, convert the object to json-string:
Gson gson = new Gson();
String myJson = gson.toJson(vp);
intent.putExtra("myjson", myjson);
In your receiving Activity, convert the json-string back to the original object:
Gson gson = new Gson();
YourObject ob = gson.fromJson(getIntent().getStringExtra("myjson"), YourObject.class);
For Kotlin it's quite the same
Pass the data
val gson = Gson()
val intent = Intent(this, YourActivity::class.java)
intent.putExtra("identifier", gson.toJson(your_object))
startActivity(intent)
Receive the data
val gson = Gson()
val yourObject = gson.fromJson<YourObject>(intent.getStringExtra("identifier"), YourObject::class.java)