Reputation: 13807
I'm sorry if this Question is already answered, i searched a lot, but i couldn't find any question with my problem.
I'm writing an android app which gets data from an internet database. My first activity retrieves the data from the database, and i try to pass a reference to the whole database to another activity.
it briefly looks briefly like this:
//server is wrapper class for my database connection/ data retrieving
Server server = new Server(...connection data...);
server.connect();
server.filldata();
And after that i try to pass this to another activity
Intent intent = new Intent(this, OtherActivity.class);
intent.putExtra("server", server); //server, and all implements Serializable
startActivity(intent);
And after this i get a java.lang.reflect.InvocationTargetException without explanation, what the problem could be.
Please if you know a way to pass an Object (except for int, string...) to another activity, help me!
Upvotes: 1
Views: 11141
Reputation: 621
For any object which needs to be passed via Bundle must implement the Parcelable or Seralizable interface.Intent provides both the interfaces:
putExtra(String name, Parcelable value)
putExtra(String name, Serializable value)
https://developer.android.com/reference/android/content/Intent.html
But it is advisable to use Parcelable as it is written specifically for Android and is light-weight in nature.
Upvotes: 0
Reputation: 68177
Your class Server
should implement interface Parcelable
in order for its object to be transferred via bundle.
See the example below, which is available here:
public class MyParcelable implements Parcelable {
private int mData;
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeInt(mData);
}
public static final Parcelable.Creator<MyParcelable> CREATOR
= new Parcelable.Creator<MyParcelable>() {
public MyParcelable createFromParcel(Parcel in) {
return new MyParcelable(in);
}
public MyParcelable[] newArray(int size) {
return new MyParcelable[size];
}
};
private MyParcelable(Parcel in) {
mData = in.readInt();
}
}
Upvotes: 2