Reputation: 31
I am writing software for Android for communication between Arduino and Android.
The Arduino sends data using serial.println
- I send the text "It works!".
The Android is receiving data in this way:
bytes = mmInStream.read(buffer);
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();
And it displays some code instead of "it works!", more exactly it displays [B@40e3f9b8
.
What is the reason and how can this problem be fixed?
Upvotes: 2
Views: 847
Reputation: 99
You have to create a string from a byte array: String strIncom = new String(buffer, 0, msg.arg1); Full example with \r\n handler:
h = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case RECIEVE_MESSAGE: // if receive massage
byte[] readBuf = (byte[]) msg.obj;
String strIncom = new String(readBuf, 0, msg.arg1); // create string from bytes array
sb.append(strIncom); // append string
int endOfLineIndex = sb.indexOf("\r\n"); // determine the end-of-line
if (endOfLineIndex > 0) { // if end-of-line,
String sbprint = sb.substring(0, endOfLineIndex); // extract string
sb.delete(0, sb.length()); // and clear
txtArduino.setText("Data from Arduino: " + sbprint); // update TextView
}
//Log.d(TAG, "...String:"+ sb.toString() + "Byte:" + msg.arg1 + "...");
break;
}
};
};
See full example program with apk and sources here
Upvotes: 1
Reputation: 179392
You just tried to print a byte array. In Java, that just prints out the type of the object [B
, followed by its address @40e3f9b8
.
If you want to print the text out, use new String(bytes)
to get a string from the bytearray (using the default charset), then print the string out.
Upvotes: 3