Reputation: 317
I want to pass a Java Socket object from one activity to another. I thought of using Parcelable for passing but cannot add the object to the parcel
public class NetworkInformation implements Parcelable {
private String ipAddress;
private String portNo;
private Socket networkSocket;
protected NetworkInformation(Parcel in) {
}
public static final Creator<NetworkInformation> CREATOR = new Creator<NetworkInformation>() {
@Override
public NetworkInformation createFromParcel(Parcel in) {
return new NetworkInformation(in);
}
@Override
public NetworkInformation[] newArray(int size) {
return new NetworkInformation[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(ipAddress);
dest.writeString(portNo);
//How to add the Socket to parcelable here ?
}
}
Upvotes: 2
Views: 222
Reputation: 56
I'm not sure if this will work, but you might try:
private String ipAddress;
private String portNo;
private Socket networkSocket;
protected NetworkInformation(Parcel in) {
ipAddress = in.readString();
portNo = in.readString();
networkSocket = new Socket(makeRealIP(ipAddress),makeRealPortNo(portNo));
}
Of course, you would have to write your own makeRealIP and makeRealPortNo to convert the strings back into useful parameters for a new Socket();
Bundle myBundle = new Bundle();
NetworkInformation myNetworkInfo;
myBundle.putParceable("myNetworkInfo",myNetworkInfo);
myNetworkInfo = (NetworkInformation)myBundle.getParceable("myNetworkInfo");
I've not tried this, and I'll bet the other folks that answered were quite correct to warn about mucking around at the socket layer. It can get a bit tricky. Good Luck.
Upvotes: 2