所以我知道还有其他的帖子解决同样的问题,我想我已经跟着他们的信,但可惜无济于事。我想了解如何获得我的应用程序与JavaScript交互。我只是希望能够从我的javascript返回一个值来我的活动。 这是我的活动:
So i know there are other posts addressing the same issue, and I think I've followed them to the letter but alas to no avail. I'm trying to learn how to get my app to interact with javascript. I just want to be able to return a value from my javascript to my activity. here is my activity:
public class JSExample extends Activity {
WebView mWebView;
String mString;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mWebView = (WebView)findViewById(R.id.mWebView);
mWebView.addJavascriptInterface(new ClsAccessor(), "accessor");
String html = getAssetsContent("jsinterface.html");
mWebView.loadDataWithBaseURL(null, html, "text/html", "UTF-8", null);
// Log.d("YO!", mString);
}
private String getAssetsContent(String filename){
.....
}
private void closeStream(BufferedReader stream) {
.....
}
class ClsAccessor{
public void setValue(String value){
JSExample.this.mString = value;
}
}
下面是包含我想要运行的JavaScript在我的WebView加载HTML文件:
Here is the html file loaded by my WebView that contains the javascript i want to run:
<!DOCTYPE html>
<html>
<head>
<script language="javascript">
accessor.setValue('Hello!');
</script>
</head>
<body>
<h1>Testing</h1>
</body>
</html>
这是行不通的。当我运行code以Log.d(哟!,mString);取消注释我得到一个空指针异常,这意味着JavaScript的从未分配一个值mString。我究竟做错了什么?
This does not work. When i run the code with "Log.d("YO!", mString);" uncommented I get a null pointer exception, which means that the javascript never assigned a value to mString. what am i doing wrong?
这可能是不正确的,我将不得不仔细检查,但它可能是由于丢失的参考。
This may not be correct, I will have to double check but it may be due to the reference being lost..
试着让你的 ClsAccessor
引用成员级别的..
Try making your ClsAccessor
reference a member level one..
public class JSExample extends Activity {
...
ClsAccessor _accessor = new ClsAccessor();
...
public void onCreate(Bundle savedInstanceState) {
...
mWebView.addJavascriptInterface(_accessor, "accessor");
...
此外,如果你通过在线调试线确实的setValue()
以往任何时候都得到所谓的管理code?
Also if you debug line by line does setValue()
ever get called in managed code?
对于什么是值得的,我有code正如我上面描述的脚本来管理接口能正常工作是干什么的,但我不是在目前测试的位置,看看是否不具有参考该类也适用。
For what it is worth, I have code that is doing as I have described above and the script to managed interface works fine, however I am not in a position currently to test and see if not having a reference to the class also works.