我正在尝试使用ObjectOutputStream将对象发送到另一台运行android的设备。我一直得到ClassNotFoundException。
我的类实现了Serializable。我没有尝试使用Parcelable实现序列化,以通过蓝牙将对象发送到另一台设备。有人试过吗? 你的意见好吗?谢谢
可序列化或可分割是否符合我的目的?
答案 0 :(得分:1)
//mmSocket is the socket i got from a bluetooth connection
//this is for sending an object
public void writeSerialized(){
Object contact = new Contact("Allen", "Patterson", "256-369-241");
try {
ObjectOutputStream oos = new ObjectOutputStream(mmSocket.getOutputStream());
oos.writeObject(contact);
oos.close();
}catch(Exception e){
Log.e(TAG, "Error ObjectOutputStream: "+e.getLocalizedMessage());
}
}
// mmInputStream是我从socket获得的流。 这是接收方
public void run() {
// Keep listening to the InputStream while connected
while (true) {
try {
ObjectInputStream ois = new ObjectInputStream(mmInStream);
Object contact = ois.readObject();
Log.i(TAG,"Contact class: "+contact);
} catch (IOException | ClassNotFoundException e) {
Log.i("ERROR", "E:"+e.getLocalizedMessage());
}
}
}
//我试图发送的对象并以其他尺寸接收
public class Contact implements Serializable{
static final long serialVersionUID = 123456789123456789L;
private String id;
private String name;
private String phoneNumber;
public Contact(){}
public Contact(String id, String name, String phoneNumber) {
this.id = id;
this.name = name;
this.phoneNumber = phoneNumber;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
}
解决方案是在应用程序的两端使用相同包名称的Serializable实现类。例如com.shared.models并为可序列化类提供相同的SerialVersionUID。为我解决了它