0

我正在使用 android 模拟器进行测试,当它执行此功能时,它会强制关闭应用程序。(E.g. String1|Sub1,Sub2,Sub3)但是,在我注释掉以下语句后,该函数成功执行并产生了 toast 消息。当我取消注释第一个 split() 语句并尝试运行测试时,它再次强制关闭应用程序。

public void readData()
{
    try
    {
        FileInputStream fin = openFileInput("data.txt");
        InputStreamReader isr = new InputStreamReader(fin);
        BufferedReader br = new BufferedReader(isr);

        String line;

        do 
        {
            line = br.readLine();

            //String[] temp = line.split("|");
            //String[] temp2 = temp[1].split(",");

            //Vector<String> nameTemp = new Vector<String>(Arrays.asList(temp2));

            //Team container = new Team(temp[0], nameTemp);
            //grpContent.add(container);

            invalidCharacterToast(line);    //Toast message
        }
        while (line != null);

        br.close();
        isr.close();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
}

日志猫:

06-27 12:13:41.446: E/AndroidRuntime(289): FATAL EXCEPTION: main
06-27 12:13:41.446: E/AndroidRuntime(289): java.lang.NullPointerException
06-27 12:13:41.446: E/AndroidRuntime(289):  at com.example.project.Start.readData(Start.java:196)
06-27 12:13:41.446: E/AndroidRuntime(289):  at com.example.project.Start.onClick(Start.java:140)
06-27 12:13:41.446: E/AndroidRuntime(289):  at android.view.View.performClick(View.java:2408)
06-27 12:13:41.446: E/AndroidRuntime(289):  at android.view.View$PerformClick.run(View.java:8816)
06-27 12:13:41.446: E/AndroidRuntime(289):  at android.os.Handler.handleCallback(Handler.java:587)
06-27 12:13:41.446: E/AndroidRuntime(289):  at android.os.Handler.dispatchMessage(Handler.java:92)
06-27 12:13:41.446: E/AndroidRuntime(289):  at android.os.Looper.loop(Looper.java:123)
06-27 12:13:41.446: E/AndroidRuntime(289):  at android.app.ActivityThread.main(ActivityThread.java:4627)
06-27 12:13:41.446: E/AndroidRuntime(289):  at java.lang.reflect.Method.invokeNative(Native Method)
06-27 12:13:41.446: E/AndroidRuntime(289):  at java.lang.reflect.Method.invoke(Method.java:521)
06-27 12:13:41.446: E/AndroidRuntime(289):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
06-27 12:13:41.446: E/AndroidRuntime(289):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
06-27 12:13:41.446: E/AndroidRuntime(289):  at dalvik.system.NativeStart.main(Native Method)
06-27 12:13:43.406: I/Process(289): Sending signal. PID: 289 SIG: 9
4

1 回答 1

4

这是一个 do-while 循环,因此您的br.readLine()语句在 null 检查之前执行,因此第一个split方法可能会针对null.

你应该这样重写它:

while ((line = br.readLine()) != null) {
    // your code
}
于 2013-06-27T12:05:33.490 回答