首页 > 解决方案 > 将字符串值解析为整数时出错

问题描述

我从蓝牙获取数据,该数据是字符串类型,我试图在 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;
                    }
                }
            }
        });

标签: javaandroidparsing

解决方案


您似乎没有收到 int 值。检查数据包含什么,也许它包含一些意想不到的字符。


推荐阅读