2015-05-23 70 views
0

我有一個通過藍牙接收數字(精確到毫秒)的函數。無法將字符串轉換爲Android Studio/Java中的整數

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

嘗試'新的整數(data.trim());'可以是'\ N' –

+0

嘗試 '敏= Integer.valueOf(數據);' – mrahmat

+0

@路易斯·費利佩·考夫曼達席爾瓦完美,就是這樣... – PrimuS

回答

1

您的data是一個字符串。當您稍後嘗試形成Integer時,將失敗。您需要使用此: myInt = new Integer(Integer.parseInt(data));