简体   繁体   中英

Object sending/receiving via Bluetooth in Android

I am trying to send an object to another device running android using ObjectOutputStream. I keep getting ClassNotFoundException.

My class implements Serializable. I haven't tried implementing serialization using Parcelable to send objects via Bluetooth to another device. Has anyone tried that? Your opinions please? thank you

Is serializable or parcelable the right way to go about my purpose?

//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 is Stream I got from socket. This is for receiving side

 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());
            }
        }
    }

//the object I am trying to send out and receive on the other size

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;
}

}

The solution is to have the Serializable implementing class on both sides of the application in the same package name. For example com.shared.models and give the serializable class the same SerialVersionUID. that solved it for me

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM