无法在Android Studio / Java中将String转换为Integer

时间:2015-05-23 15:38:49

标签: java android bluetooth

我有一个通过蓝牙接收数字(精确到毫秒)的功能。

byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
final String data = new String(encodedBytes, "UTF-8");
readBufferPosition = 0;

started = "";
int myInt;
if (data != "") {
  try{
    myInt = new Integer(data);
    long seconds = TimeUnit.MILLISECONDS.toSeconds(myInt);
  }catch(NumberFormatException ex){
    System.err.println("NumberFormatException "+ ex.getMessage());
  }
  ...
} else {
  ...
}

以上尝试抛出:

NumberFormatException Invalid int: "8250

我认为收到的数据只包含毫秒数,但是当我这样做时,我怎么能找到它呢

myLabel.setText(data);

它告诉我:8250

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您的data是一个字符串。当您稍后尝试形成一个Integer时,这会失败。你需要使用这个: myInt = new Integer(Integer.parseInt(data));