在android中将数字字符串转换为整数

时间:2014-06-12 06:42:07

标签: java android parseint android-handler string-conversion

在下面的代码中,当我尝试将msgStr转换为整数时,app force关闭。谁能告诉我原因?是因为msgStr格式不正确吗? 注意:msg是一个obj通过处理程序。 msgStr是一个数字字符串。

MainActivity代码:

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;
}

蓝牙连接线程:

  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;
        }
    }
  }

现在有人能说出问题所在吗?另外,如果mmInStream由数字数据组成,那么如何区分和存储字节数组缓冲区中3位数据的2位数据?

6 个答案:

答案 0 :(得分:0)

尝试

String msgString = new String(...);

答案 1 :(得分:0)

更改此

String msgStr = String(byteArr);

String msgStr = new String(byteArr);

这篇文章可以帮助您How To Convert Byte[] Array To String In Java

答案 2 :(得分:0)

String s = new String(byteArr);
System.out.println("Output : " + s);

答案 3 :(得分:0)

这是因为您将字节数组转换为字符串,但这不起作用。您需要使用this constructor

String msgStr = new String(byteArr, "UTF-8");

当然,UTF-8会根据您使用的字符集而有所不同。

答案 4 :(得分:0)

首先通过以下代码将Byte转换为String。

String msg = new String(bytes, "UTF-8");

然后将您的字符串转换为整数,如下所示。

int m = Integer.parseInt(msg);

答案 5 :(得分:0)

尝试直接将邮件转换为String:

String msgStr = (String)msg.obj;

如果这不起作用也尝试将其转换为Integer,则可能检索到的String不是整数。


您也可以直接将Handler消息作为整数发送,而无需转换它:

yourhandlername.obtainMessage(what, arg1, arg2, obj).sendToTarget();

arg1 :是一个整数

arg2 :是一个整数

所以,收到时:

int val = msg.arg1;