How can I pass an object of a custom type from one Activity to another using the
putExtra()
method of the class Intent?
I use Gson with its so powerful and simple api to send objects between activities,
Example
// This is the object to be sent, can be any object
public class AndroidPacket {
public String CustomerName;
//constructor
public AndroidPacket(String cName){
CustomerName = cName;
}
// other fields ....
// You can add those functions as LiveTemplate !
public String toJson() {
Gson gson = new Gson();
return gson.toJson(this);
}
public static AndroidPacket fromJson(String json) {
Gson gson = new Gson();
return gson.fromJson(json, AndroidPacket.class);
}
}
2 functions you add them to the objects that you want to send
Usage
Send Object From A to B
// Convert the object to string using Gson
AndroidPacket androidPacket = new AndroidPacket("Ahmad");
String objAsJson = androidPacket.toJson();
Intent intent = new Intent(A.this, B.class);
intent.putExtra("my_obj", objAsJson);
startActivity(intent);
Receive In B
@Override
protected void onCreate(Bundle savedInstanceState) {
Bundle bundle = getIntent().getExtras();
String objAsJson = bundle.getString("my_obj");
AndroidPacket androidPacket = AndroidPacket.fromJson(objAsJson);
// Here you can use your Object
Log.d("Gson", androidPacket.CustomerName);
}
I use it almost in every project i do and I have no performance issues.