java - 将字符串值解析为整数时出错
问题描述
我从蓝牙获取数据,该数据是字符串类型,我试图在 android studio 中将此值解析为整数,我收到此错误“java.lang.NumberFormatException: Invalid int:”所以我该怎么做才能解决它. 这是我的java代码:
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;
}
}
}
});
解决方案
您似乎没有收到 int 值。检查数据包含什么,也许它包含一些意想不到的字符。
推荐阅读
- xcode - 在“NSProcessInfo”类型的对象上找不到属性“isiOSOnMac”
- c++ - 根据 Rcpp.h 为自定义类扩展 Rcpp::as
- dictionary - 计算dict中的关键字
- python - 了解函数式编程的副作用
- ckeditor5 - 如何将自定义元素添加到 CKEditor 5?
- excel - PowerShell 从导入的 Excelsheet 动态创建 ADUsers
- r - 将坐标、半径和站点类型数据从 .csv 转换为 R 中的栅格
- okhttp - 我可以使用 OkHttp 将本地 IP 地址绑定到我的 SSLSocketFactory 吗?
- app-store - Appstore Connect API - 应用分析报告
- html - CSS | 100% 高度元素中的空白