简体   繁体   中英

Is there any chance of this code printing null?

String readwidget(int a, int b){     

    WidgetChild readwidget = Widgets.get(a,b);            
    if(readwidget.getText() != null){         
        Task.sleep(10);
        System.out.println(readwidget.getText());
        return readwidget.getText();
    }

    Task.sleep(10);
    return    GOT_NULL; 

}

while(readFirstWidget.equals(GOT_NULL) && t5.isRunning()) {     

    readFirstWidget = readwidget(1184, 13);
    Task.sleep(50,80);

}

This piece of code is crashing with nullpointerexception once in while(1 out of 50 time) and it prints null at that point of time which it should not. Can anyone please help me to find out the causes? Thanks in advance.

You mention in a comment that Widgets.get(a,b) can return null . Given that, you need to guard against that possibility by checking the return value from the method for null prior to actually calling any instance methods on it. You aren't doing that, and so you are crashing in that case.

All you need to do is add the null check and your code should be fine:

WidgetChild readwidget = Widgets.get(a,b);            
if(readwidget != null && readwidget.getText() != null) { 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM