Exception in thread “AWT-EventQueue-0” java.lang.N

2019-08-01 13:33发布

I am trying to execute Javascript function called "returnAllLinkTexts()" on the DOM html page loaded via my Java application. Below line is executed by a Swing Buton.

myscript = browser.executeJavascript("returnAllLinkTexts()").toString(); //Line 407

Once in a while I get the following exception. The Java application does not terminate or crash.

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException com.demo.Main$BigButtonListener.actionPerformed(Main.java:407)

I have tried the following to keep retrying about 20 times but it doesn't even reach this point. Exception is raised immediately @ 407.

int st = 0;
while (myscript == null){
 myscript = browser.executeJavascript("gogo()").toString();                              if (myscript != null) break;
 if (shit == 20) break;
 sht++;
}

UPDATE:

This is the Javascript function returnAllLinkTexts();

function returnAllLinkTexts(){  
var mydata = new Array();

$('a', document).each(function() {
    mydata.push($(this).text()); 
});

return mydata;
}

3条回答
在下西门庆
2楼-- · 2019-08-01 13:39

The only thing I can think of why returnAllLinkTexts is breaking (thus you get null) is when it's called before jQuery was loaded.

If possible, try calling browser.executeJavascript after the page finished loading otherwise check for null as others already suggested and you can keep trying to invoke it (using timer for example) until it's not null.

Edit: since you're already using the return value as string, you can return string to begin with, for example:

return mydata.join(",");

Will return the links text separated with comma.

查看更多
在下西门庆
3楼-- · 2019-08-01 13:49

Don't unconditionally call toString() on a return value which may be null. Always check first for null!

查看更多
在下西门庆
4楼-- · 2019-08-01 14:02

You're calling toString() on a potentially null object.

-> Firstly, I would surround with a try-catch block

But the question is why is the return value a possible-null? Check your return value in the function..

Nur

查看更多
登录 后发表回答