Exception in thread “AWT-EventQueue-0” java.lang.NullPointerException when trying to execute Javascript

∥☆過路亽.° 提交于 2019-12-25 00:33: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;
}

回答1:


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.




回答2:


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




回答3:


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



来源:https://stackoverflow.com/questions/4732618/exception-in-thread-awt-eventqueue-0-java-lang-nullpointerexception-when-tryin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!