I am currently working on sending an object (Shopping) from an user to another via Bluetooth.
When i click on the "SEND" button from my server phone, the object Shopping is sent correctly, and i print it on my terminal via Log.d(StringNameOfShopping)
But i can only send bytes[]
array, that is transformed to int bytes then creates a new String(buffer[], offset, bytes)
So is there a method to cast from String (that has my object Shopping reference for example : Shopping@bd429a9
) to a Shopping object ?
Here is my methods for listening to Input and Output.
public void run(){
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
// Read from the InputStream
try {
bytes = mmInStream.read(buffer);
String incomingMessage = new String(buffer, 0, bytes);
Log.d(TAG, "InputStream: " + incomingMessage);
} catch (IOException e) {
Log.e(TAG, "write: Error reading Input Stream. " + e.getMessage() );
break;
}
}
}
//Call this from the main activity to send data to the remote device
public void write(byte[] bytes) {
String text = new String(bytes, Charset.defaultCharset());
Log.d(TAG, "write: Writing to outputstream: " + text);
try {
mmOutStream.write(bytes);
} catch (IOException e) {
Log.e(TAG, "write: Error writing to output stream. " + e.getMessage() );
}
}
And here are my Serialize/Deserialize methods (But where should i put them ? In my MainActivity, or Shopping Class? Or Bluetooth class ?
public byte[] serialize(Shopping shopping) throws IOException {
ByteArrayOutputStream b = new ByteArrayOutputStream();
ObjectOutputStream o = new ObjectOutputStream(b);
o.writeObject(shopping);
return b.toByteArray();
}
//AbstractMessage was actually the message type I used, but feel free to choose your own type
public static Shopping deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
ByteArrayInputStream b = new ByteArrayInputStream(bytes);
ObjectInputStream o = new ObjectInputStream(b);
return (Shopping) o.readObject();
}