尝试解析字符串时,我的应用程序崩溃

时间:2019-10-09 08:11:20

标签: java android multithreading

我试图解析一个字符串以计算产品总价,但是当我使用“ Integer.parseInt”时,我的应用程序崩溃了。  我知道我必须初始化一个字符串数组,导致指令“ Integer.parseInt”无法解析NULL,但是我不知道问题是我的数组元素来自于拆分字符串。请帮助我... 我的代码:

    class Thread2 implements Runnable {//recieve
        @Override
        public void run() {
            while (true) {
                try {
                    final String message = input.readLine();
                    if (message != null) {
                        owner.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                String[] a = message.split("\\#");
                                int n = a.length;
                                    for(int i=1;i<n;i++){

                                        String[]    b =a[i].split("\\*");

                                             tee.append(b[0]+"                    "+b[1]+"\n");
                                             y.append(b[1]+"*");

                                             P1=Integer.parseInt(b[1]);

                                             //total = total+p1[i];


                                    }



                                te.setText(Integer.toString(total));



                            }
                        });
                    } else {
                        Thread myThred = new Thread(new Thread21());
                        myThred.start();
                        return;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

2 个答案:

答案 0 :(得分:1)

请使用try-catch处理ui块中的异常。

    try {
        String[]    b =a[i].split("\\*");

        tee.append(b[0]+"                    "+b[1]+"\n");
        y.append(b[1]+"*");

        P1=Integer.parseInt(b[1]);

        //total = total+p1[i];
    } catch(Exception ex) {
    }

除此之外,您可以在Exception块中使用 catch 而不是 IOException 来处理各种异常,避免崩溃。谢谢

编辑方式:

     } catch (Exception e) {
           e.printStackTrace();
     }

代替:

     } catch (IOException e) {
           e.printStackTrace();
     }

答案 1 :(得分:0)

尝试一下。默认情况下,将P1的值设置为0,并且仅当数组在b [1]处具有值且不为null时,才从b [1]中获取值。

P1 = 0;
if(b.length() > 1){
    if(b[1] != null)
        P1=Integer.parseInt(b[1]);
}
....