jwheels
jwheels

Reputation: 527

Convert object to byte array (to send it through a socket). then convert it back

I have the following class definition:

public class Message {
     private String sender, text;

     public Message(String sender, String text) {
         this.sender = sender;
         this.text = text;
     }

}

I would like to be able to send an instance of this Message class over a bluetooth socket. In order to do this, it will need to be converted into a byte[]. After it has been sent, I need to convert it back to a Message object (on the other side of the socket). How can I achieve this?

Upvotes: 2

Views: 2408

Answers (3)

Emmanuel Devaux
Emmanuel Devaux

Reputation: 3407

Two possible answers Serializable vs Parcelable

Serializable relatively easy to implement but not efficient in term of memory and CPU

http://developer.android.com/reference/java/io/Serializable.html

Parcelable more complex to implement but more efficient in term of memory and CPU

http://developer.android.com/reference/android/os/Parcelable.html

Upvotes: 2

thob
thob

Reputation: 1

You could define a function, which returns a byte[] and just call it before you send it per bluetooth. The byte-array could be like { sendersize, textsize, sender, text }. Define also a function which reverts the process and call it on the other side.

Upvotes: 0

John
John

Reputation: 2425

Look into serialization.

http://developer.android.com/reference/java/io/Serializable.html

Upvotes: 0

Related Questions