cannot convert string to int after receiving data in java - java

i have arduino that send 2 int and the int was separate by " : "
for example my arduino send data = 12315: 15123
after i send that data using bluetooth, i receive the data in smartphone and i need that 2 value that i receive become int again
this is was my part code on my android
void beginListenForData()
{
final Handler handler = new Handler();
final byte delimiter = 10; //This is the ASCII code for a newline character
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];
workerThread = new Thread(new Runnable()
{
public void run()
{
while(!Thread.currentThread().isInterrupted() && !stopWorker)
{
try
{
int bytesAvailable = mmInputStream.available();
if(bytesAvailable > 0)
{
byte[] packetBytes = new byte[bytesAvailable];
mmInputStream.read(packetBytes);
for(int i=0;i<bytesAvailable;i++)
{
byte b = packetBytes[i];
if(b == delimiter)
{
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
final String data = new String(encodedBytes, "US-ASCII");
readBufferPosition = 0;
handler.post(new Runnable()
{
public void run()
{
String[] tmp;
String lol,dam;
tmp = data.split(":");
try
{
lol = String.valueOf(crypt[0])+":"+String.valueOf(crypt[1]);
derajat.setText(lol);
}
catch (NumberFormatException nfe)
{
// bad data - set to sentinel
crypt[0] = Integer.MIN_VALUE;
crypt[1] = Integer.MIN_VALUE;
derajat.setText("none");
}
dam = tmp[0]+":"+tmp[1];
myLabel.setText(dam);
//derajat.setText(data);
}
});
}
else
{
readBuffer[readBufferPosition++] = b;
}
}
}
}
catch (IOException ex)
{
stopWorker = true;
}
}
}
});
workerThread.start();
}
as you can see that after '\n' data will be process
first i split using data.split() and i get 2 value that stored in tmp
after that i parse that value to crypt[0] and crypt[1]
i set text to derajat to see my value
and i set text the result in myLabel too
i can see my value in myLabel but i cant convert it to int because i see nothing in label derajat
can somebody help me why i cant convert int after receiving that data ??

If the received data from your Arduino is in fact as you have specified:
"12315: 15123"
Then what is happening is that you are getting a NumberFormatException which you do catch but really have no way of knowing other than derajat will contain nothing (or "none")....which is exactly what you are experiencing.
The reason you would get a NumberFormatException is because there is a white-space directly after the colon (:) delimiter so when you try to carry out:
crypt[1] = Integer.parseInt(tmp[1]);
(tmp[1] actually holds " 15123") a NumberFormatException is thrown. The Integer.parseInt() method will not handle white-spaces within the numerical string. To remedy this trim your split strings, for example:
crypt[0] = Integer.parseInt(tmp[0].trim());
crypt[1] = Integer.parseInt(tmp[1].trim());
or split with:
tmp = data.split(": ");

Related

Error when I am parsing string value to integer

I get the data from bluetooth , this data it is string type and I am trying to parse this value to integer in android studio and I get this error "java.lang.NumberFormatException: Invalid int:" so what can I do to resolve it.
This is my java code :
final Handler handler = new Handler();
final byte delimiter = 10; //This is the ASCII code for a newline character
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];
workerThread = new Thread(new Runnable() {
public void run() {
while(!Thread.currentThread().isInterrupted() && !stopWorker) {
try {
int bytesAvailable = inputStream.available();
if (bytesAvailable > 0) {
byte[] packetBytes = new byte[bytesAvailable];
inputStream.read(packetBytes);
for (int i = 0; i < bytesAvailable; i++) {
byte b = packetBytes[i];
if (b == delimiter) {
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
final String data = new String(encodedBytes, "US-ASCII");
readBufferPosition = 0;
handler.post(new Runnable() {
public void run() {
if(Integer.parseInt(data)<10) {//Here the error
addNotification();
}
System.out.println(data);
}
});
} else {
readBuffer[readBufferPosition++] = b;
}
}
}
} catch (IOException ex) {
stopWorker = true;
}
}
}
});
I don't know what value do you receive in data. but I can say that NumberFormatException comes when you try to convert a string into Int which is not valid Int.
Example :
String data="ABC";
will throw an exception while converting it into Integer. As "ABC" is not an integer.
Hence could you check what value exactly are you getting in data?
Also, add a try-catch block
try{
int i = Integer.parseInt(input);
} catch(NumberFormatException ex){ // handle your exception
...
}
when you use Integer.parseInt(String), your string data must only have numbers or ASCII value of + and - otherwise, it throws NumberFormatException.
public static int parseInt(String s)
throws NumberFormatException
Parses the string argument as a signed decimal integer. The characters
in the string must all be decimal digits, except that the first
character may be an ASCII minus sign '-' ('\u002D') to indicate a
negative value or an ASCII plus sign '+' ('\u002B') to indicate a
positive value.
documentation
It seems that you are not reciving an int value. Check what data contains, maybe it contains some character unexpected.

Receive string via Bluetooth android (without line feed or Carriage Return)

There are a lot of questions on stack overflow on how to receive data (string) from a Bluetooth device but I have never seen a question on how to receive data (string) without checking for LF or CR.
This code works perfectly when the device send a LF at the end of the String:
final Handler handler = new Handler();
final byte delimiter = 10; //ASCII code for Line Feed
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];
try {
inStream = btSocket.getInputStream();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
Thread workerThread = new Thread(new Runnable() {
#Override
public void run() {
while (!Thread.currentThread().isInterrupted() && !stopWorker) {
try {
int bytesAvailable = inStream.available();
if (bytesAvailable > 0) {
byte[] packetBytes = new byte[bytesAvailable];
inStream.read(packetBytes);
for (int i = 0; i < bytesAvailable; i++) {
byte b = packetBytes[i];
if (b == delimiter) {
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
final String data = new String(encodedBytes, "US-ASCII");
readBufferPosition = 0;
handler.post(new Runnable() {
public void run() {
//test
textview1.setText(data);
}
});
} else {
readBuffer[readBufferPosition++] = b;
}
}
}
} catch (IOException ex) {
stopWorker = true;
}
}
}
});
workerThread.start();
But the device that sends the string does not send a Line feed neither a CR at the end. I have tried many things (also the Bluetooth guide from Google (http://developer.android.com/guide/topics/connectivity/bluetooth.html)). I want to receive all the data that is send to the app (and for testing display the received String in a textview).
Thanks in advance,
Michielvk
Assuming all strings start with a "1" character, you should be able to read the second to last string by replacing final byte delimiter = 10; by final byte delimiter = 49; (since 49 is decimal representation of "1" in ASCII table).
There's no way to read the last string (and assert you're reading the full string, not only a part) if there's no suffix delimiter.
EDIT :
You gave the protocol's documentation in this comment feed. The doc says :
The result string [...] consists of 38 ASCII characters.
According to the fact that each response consists of 38 ASCII characters, you should be able to read all messages by replacing :
if (b == delimiter) {
with :
if (readBufferPosition >= 37) {

Buffered Reader for Android Streaming from Bluetooth

Hey guys so I'm trying to read a stream from a bluetooth device continuously streaming integers like this:
-11
121
123
1234
-11
I have everything working with some code I found online, but to do some of the processing the numbers need to be ints as opposed to Strings, parseInt is taking up too much CPU, and I tried using a buffered stream with no avail.
Here is the current method:
void beginListenForData()
{
final Handler handler = new Handler();
final byte delimiter = 10; //This is the ASCII code for a newline character
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];
workerThread = new Thread(new Runnable()
{
public void run()
{
while(!Thread.currentThread().isInterrupted() && !stopWorker)
{
try
{
int bytesAvailable = mmInputStream.available();
if(bytesAvailable > 0)
{
byte[] packetBytes = new byte[bytesAvailable];
mmInputStream.read(packetBytes);
for(int i=0;i<bytesAvailable;i++)
{
byte b = packetBytes[i];
if(b == delimiter)
{
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
final String data = new String(encodedBytes, "US-ASCII");
readBufferPosition = 0;
handler.post(new Runnable()
{
public void run()
{
myLabel.setText(data);
}
});
}
else
{
readBuffer[readBufferPosition++] = b;
}
}
}
}
catch (IOException ex)
{
stopWorker = true;
}
}
}
});
workerThread.start();
}
If it makes a difference, the data is coming from an Arudino, which I can modify the way it streams.
Thanks!
Use a DataInputStream wrapped around a BufferedInputStream, and the readInt() method. This assumes network byte order in the integers of course.
Forget all this arraycopy() stuff.

Converting file into hex dump

My output is reflecting the file that I am needing to process into hex values but my hex values are not being reflected in the output. Why isn't my file being converted into hex values?
public class HexUtilityDump {
public static void main(String[] args) {
FileReader myFileReader = null;
try {
myFileReader = new FileReader("src/hexUtility/test.txt");
} catch(Exception ex) {
System.out.println("Error opening file: " + ex.getLocalizedMessage());
}
BufferedReader b = null;
b = new BufferedReader(myFileReader);
//Loop through all the records in the file and print them on the console
while (true){
String myLine;
try {
myLine = b.readLine();
//check for null returned from readLine() and exit loop if so.
if (myLine ==null){break;}
System.out.println(myLine);
} catch (IOException e) {
e.printStackTrace();
//it is time to exit the while loop
break;
}
}
}
Here is the code to pull the file through the conversion
public static void convertToHex(PrintStream out, File myFileReader) throws IOException {
InputStream is = new FileInputStream(myFileReader);
int bytesCounter =0;
int value = 0;
StringBuilder sbHex = new StringBuilder();
StringBuilder sbText = new StringBuilder();
StringBuilder sbResult = new StringBuilder();
while ((value = is.read()) != -1) {
//convert to hex value with "X" formatter
sbHex.append(String.format("%02X ", value));
//If the character is not convertible, just print a dot symbol "."
if (!Character.isISOControl(value)) {
sbText.append((char)value);
} else {
sbText.append(".");
}
//if 16 bytes are read, reset the counter,
//clear the StringBuilder for formatting purpose only.
if(bytesCounter==15) {
sbResult.append(sbHex).append(" ").append(sbText).append("\n");
sbHex.setLength(0);
sbText.setLength(0);
bytesCounter=0;
}else{
bytesCounter++;
}
}
//if still got content
if(bytesCounter!=0){
//add spaces more formatting purpose only
for(; bytesCounter<16; bytesCounter++){
//1 character 3 spaces
sbHex.append(" ");
}
sbResult.append(sbHex).append(" ").append(sbText).append("\n");
}
out.print(sbResult);
is.close();
}
You never call convertToHex, remove the file reading from your main() method. It appears you wanted to do something like,
File f = new File("src/hexUtility/test.txt");
convertToHex(System.out, f);

How to get proper values from Polar heart rate monitor

My android application is getting data from Polar Heart Rate Monitor through Bluetooth connection.
My problem is that I am getting such a string:
��������������������������������������������������
My code for getting the data:
final Handler handler = new Handler();
final byte delimiter = 10; //This is the ASCII code for a newline character
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];
workerThread = new Thread(new Runnable()
{
public void run()
{
while(!Thread.currentThread().isInterrupted() && !stopWorker)
{
try
{
int bytesAvailable = mmInputStream.available();
if(bytesAvailable > 0)
{
byte[] packetBytes = new byte[bytesAvailable];
mmInputStream.read(packetBytes);
for(int i=0;i<bytesAvailable;i++)
{
byte b = packetBytes[i];
if(b == delimiter)
{
byte[] encodedBytes = new byte[readBufferPosition];
// System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
final String data = new String(encodedBytes, "ASCII");
readBufferPosition = 0;
handler.post(new Runnable()
{
public void run()
{
pulsText.setText(data);
}
});
}
else
{
readBuffer[readBufferPosition++] = b;
}
}
}
}
catch (IOException ex)
{
stopWorker = true;
}
}
}
});
workerThread.start();
I tried to change this line in few ways but I am still getting incorrect data:
final String data = new String(encodedBytes, "ASCII");
How can I solve this issue ?
Please help !!!
The sensor doesn't give you printable strings (like e.g. NMEA does) but binary data that you need to parse. You could look into the MyTracks Polar Sensor data parser for inspiration.
You are using available and read incorrectly (but the way you use you could have luck most of the time).
The Units of Measurement (based on Raspberry Pi Challenge at JavaOne) "Heart of Glass" project shows, how this can be parsed into a typesafe Heartbeat Unit for display or transfer to other systems.

Categories

Resources