当原始格式时,我可以从USB串行工作获得该字符串。但是一旦我尝试使用Double.valueOf或其他方法将其转换为编号,应用就会崩溃。
public void onReceivedData(byte[] arg0) {
String data = null;
try {
data = new String(arg0, "UTF-8");
Double waterLevel=Double.valueOf(data);
tvAppend(textView, waterLevel+"m");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
使用此方法时,以上方法有效,并且仅尝试将String转换为Double或Float会造成麻烦:
String waterLevel=data+"m";
错误消息:
2019-02-05 19:02:06.746 915-5126/? E/AwareLog: CPUFeatureAMSCommunicator: set app boost but type is unknown
2019-02-05 19:02:06.824 421-450/? E/DynamicFpsPolicy: FpsInfo: 1a500000000 can not find FpsPolicyService
2019-02-05 19:02:07.683 915-1498/? E/TouchFilter: setTouchFilter LOG Enable prameter: 0
2019-02-05 19:02:08.237 421-450/? E/DynamicFpsPolicy: FpsInfo: 1a500000000 can not find FpsPolicyService
2019-02-05 19:02:08.454 12270-12270/com.jorc.loggergeneral.jorclogger E/SpannableStringBuilder: SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
2019-02-05 19:02:08.455 12270-12270/com.jorc.loggergeneral.jorclogger E/SpannableStringBuilder: SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
2019-02-05 19:02:09.432 12270-12467/? E/AndroidRuntime: FATAL EXCEPTION: Thread-6
Process: com.jorc.loggergeneral.jorclogger, PID: 12270
java.lang.NumberFormatException: empty String
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1842)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.lang.Double.parseDouble(Double.java:539)
at java.lang.Double.valueOf(Double.java:503)
at com.jorc.loggergeneral.jorclogger.MainActivity$1.onReceivedData(MainActivity.java:55)
at com.felhr.usbserial.UsbSerialDevice$WorkerThread.onReceivedData(UsbSerialDevice.java:209)
at com.felhr.usbserial.UsbSerialDevice$WorkerThread.run(UsbSerialDevice.java:184)
2019-02-05 19:02:09.483 915-1082/? E/InputDispatcher: channel '4af7ed1 com.jorc.loggergeneral.jorclogger/com.jorc.loggergeneral.jorclogger.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
2019-02-05 19:02:09.535 421-450/? E/DynamicFpsPolicy: FpsInfo: 1a500000000 can not find FpsPolicyService
2019-02-05 19:02:09.706 915-1284/? E/TouchFilter: setTouchFilter LOG Enable prameter: 0
2019-02-05 19:02:09.938 1135-1135/? E/FullInputEventModel: onStartInput event aborted: ejh: could not obtain extracted text (class ejh)
2019-02-05 19:02:10.976 485-485/? E/Thermal-daemon: [battery] temp_new :32 temp_old :31
2019-02-05 19:02:10.979 485-485/? E/Thermal-daemon: Report temperature: [battery] temp :32 report_threshold:1
2019-02-05 19:02:11.731 915-1284/? E/TouchFilter: setTouchFilter LOG Enable prameter: 0
答案 0 :(得分:0)
您的答案在堆栈跟踪中。您尝试解析一个空字符串。 有时尝试使用调试器...
答案 1 :(得分:0)
我可以使用流行语来解决这个问题。您不能只在第一行使用if短语来避免它:
if(data.length()!=0 && data.length()>0){
try {
tvAppend(textView, Double.parseDouble(data)*6 + "m\n");
} catch(Exception e) {
// or some value to mark this field is wrong. or make a function
}
}