Android ArrayList奇怪的空指针异常

时间:2013-04-07 02:55:01

标签: java android arraylist nullpointerexception

我对此代码有疑问:

 for(int i2=0;i2<ftdata.size();i2++){
        System.out.println("FTDATASIZE: " +ftdata.get(i2)); // here pass and shows null
        String test=ftdata.get(i2); // here gets Null Pointer Exception ????
        if(test.equals("null")){

        }
    }

System.out在LogCat“FTDATASIZE:null”中显示但是我收到此行错误“String test = ftdata.get(i2);”我不明白吗?为什么我得到Null Pointer Exception?

    04-07 05:42:36.309: I/System.out(12983): STDATASIZE: 1
    04-07 05:42:36.309: I/System.out(12983): FTDATASIZE: 1
    04-07 05:42:36.309: I/System.out(12983): FTDATASIZE: null
    04-07 05:42:36.309: W/dalvikvm(12983): threadid=10: thread exiting with uncaught exception (group=0x40166560)
    04-07 05:42:36.309: E/AndroidRuntime(12983): FATAL EXCEPTION: Thread-11
    04-07 05:42:36.309: E/AndroidRuntime(12983): java.lang.NullPointerException
    04-07 05:42:36.309: E/AndroidRuntime(12983):    at soft.ProDb.distanceRunsMonthly(ProDb.java:22718)
    04-07 05:42:36.309: E/AndroidRuntime(12983):    at soft.ProDb.runsMonthly(ProDb.java:22593)
    04-07 05:42:36.309: E/AndroidRuntime(12983):    at soft.SHtmlM.exportALLHtml(StringaHtmlM.java:111)
    04-07 05:42:36.309: E/AndroidRuntime(12983):    at soft.ProDb$1.run(ProDb.java:12714)
    04-07 05:42:36.309: E/AndroidRuntime(12983):    at java.lang.Thread.run(Thread.java:1019)

行 修正了

这对我有用

 if(ftdata.size()==1&& ftdata.get(0)==null){
        ftdata=stdata;
    }

只是想测试ftdata.get(0)是否为null

2 个答案:

答案 0 :(得分:4)

空指针位于if(test.equals("null")){行上,因为testnull,您正试图在其上调用.equals()

如果您要检查String是否为null,请改用if (test == null)

如果您要检查字符串的值是否为“null”,请改用if ("null".equals(test))

答案 1 :(得分:1)

试试这个:

for(int i2=0;i2<ftdata.size();i2++){
        System.out.println("FTDATASIZE: " +ftdata.get(i2));
        String test; 
        if(ftdata.get(i2)!=null){
            test = ftdata.get(i2);
        }
    }