In the following code, when i try to convert msgStr to integer the app force closes. Could anyone tell me the reason? Is it because msgStr is not in proper format? Note: msg is an obj got through handler. msgStr is a numeric string.
MainActivity code:
private handleMessage(Message msg){
byte[] byteArr = (byte[])msg.obj;
String msgStr = new String(byteArr,"utf-8");
try{
int val = Integer.parseInt(msgStr);
}catch(Exception e){
e.printStackTrace;
}
Bluetooth connection thread:
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
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) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI activity
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
break;
}
}
}
Now can anyone tell what can be the problem? Also if the mmInStream consists of numeric data, then how to differentiate and store 2-digit data from 3 digit data in the byte array buffer?
尝试
String msgString = new String(...);
Change this
String msgStr = String(byteArr);
to
String msgStr = new String(byteArr);
This post may help you How To Convert Byte[] Array To String In Java
String s = new String(byteArr);
System.out.println("Output : " + s);
It's because you're casting the byte array to a string and that won't work. You need to use this constructor :
String msgStr = new String(byteArr, "UTF-8");
Of course, the UTF-8 varies based on the character set you're using.
First of all convert Byte to String by following code.
String msg = new String(bytes, "UTF-8");
Then convert your string into integer as follow.
int m = Integer.parseInt(msg);
try to directly convert the message to String:
String msgStr = (String)msg.obj;
and if this not working also try to not convert it to Integer
, may be the String
retrieved isn't an integer.
Also you can send the Handler message directly as integer without having to convert it:
yourhandlername.obtainMessage(what, arg1, arg2, obj).sendToTarget();
arg1 : is an Integer
arg2 : is an Integer
So, when receiving:
int val = msg.arg1;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.