I am trying to take serial data from a TTL output device, pass it through a JY-MCU dongle and read it on my Android phone. The data is sent as a 4 digit ASCII decimal number followed by carriage return and line feed.
Using BluetoothChat, I can see the transmitted number correctly on the phone but I want to manipulate the number within the app and then send the result of the manipulation to the screen.
I only need to read the data, not send it.
Looking at the code in BluetoothChat.java I thought I would need to convert the string created in MESSAGE_READ to an Integer value, manipulate this integer number, convert it back to a string and send this result to the display.
Is this the right way to go about this? I have tried using Integer.parseInt() and String.valueOf() but without success.
I can post a simple section of the code showing what I am trying to do but thought I might be making a simple mistake which somebody can point out first.
Thanks for any suggestions
David
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf,0, msg.arg1);
//remove any leading zero's
String readMessages = readMessage.replaceAll("^0*", "");
//remove any leading zero's
// Declare Integer
int newMessage;
// give the integer a value
newMessage = Integer.valueOf(readMessages);
// try some simple division
newMessage = newMessage / 100;
// back to a string
String finalMessage = Integer.toString(newMessage);
// display the result
mConversationArrayAdapter.add(mConnectedDeviceName+": " + finalMessage);
Stacktrace
01-25 18:09:12.905: E/AndroidRuntime(5413): FATAL EXCEPTION: main
01-25 18:09:12.905: E/AndroidRuntime(5413): java.lang.NumberFormatException: Invalid int: “”
01-25 18:09:12.905: E/AndroidRuntime(5413): at java.lang.Integer.invalidInt(Integer.java:138)
01-25 18:09:12.905: E/AndroidRuntime(5413): at java.lang.Integer.parseInt(Integer.java:359)
01-25 18:09:12.905: E/AndroidRuntime(5413): at java.lang.Integer.parseInt(Integer.java:332)
The regular expression you are using is not correct as you can wonder by the fact that it returns “” (empty string) when something like “00” or “0” is the input. I suggest you to use the regular expression in the code below.
For your convenience I give you a simple test program to check if the regexp fullfil your needs. Feel free to add more tests if you are in doubt.
Pay attention that I prefer to return 0 when the parsing has some problem, you could decide to return null or a different integer (-1?).