有没有办法使用WebView将JavaScript中的对象(类实例)提取到Android?
我正在尝试提取在 JavaScript 中创建的对象和列表,以便在 Android 应用程序中使用它们。 (我已成功提取单个值。)我正在使用 addJavaScriptInterface 方法来实现此目的。
在 test.html 中,我有以下脚本代码: (我尝试过不使用“.slice()”,但也不起作用)
function getList(){
var categoryTotals = {};
categoryTotals[0] = 1;
categoryTotals[1] = 2;
categoryTotals[2] = 3;
return categoryTotals.slice();
}
并且 WebViewClient 的 onPageFinished 方法包含以下代码:
mWebView.loadUrl("javascript:window.HTMLOUT.callAndroidList(getList());");
我的 JavaScriptInterface 具有以下功能:
public void callAndroidList(final List list){
myList = list;
Log.d("ListTest" , "LIST 1 >>>>>>>>>>>>> " + ListTest.myList.get(0));
Log.d("ListTest" , "LIST 2 >>>>>>>>>>>>> " + ListTest.myList.get(1));
Log.d("ListTest" , "LIST 3 >>>>>>>>>>>>> " + ListTest.myList.get(2));
}
当我运行此代码时,我收到 NullPointerException 说 callAndroidList 的参数 list ,为空。我对 JavaScript 的了解不多,所以我认为这可能与 JavaScript 对象实例的创建和删除有关。
你能帮我一下吗?提前致谢。
I am trying to extract objects and lists created in JavaScript to use them inside Android application. (I have succeeded in extracting single values.) I am using addJavaScriptInterface method to implement this.
Inside test.html, I have the following script code:
(I've tried without ".slice()" but did not work either)
function getList(){
var categoryTotals = {};
categoryTotals[0] = 1;
categoryTotals[1] = 2;
categoryTotals[2] = 3;
return categoryTotals.slice();
}
And the WebViewClient's onPageFinished method contains the following code:
mWebView.loadUrl("javascript:window.HTMLOUT.callAndroidList(getList());");
My JavaScriptInterface has the following function:
public void callAndroidList(final List list){
myList = list;
Log.d("ListTest" , "LIST 1 >>>>>>>>>>>>> " + ListTest.myList.get(0));
Log.d("ListTest" , "LIST 2 >>>>>>>>>>>>> " + ListTest.myList.get(1));
Log.d("ListTest" , "LIST 3 >>>>>>>>>>>>> " + ListTest.myList.get(2));
}
When I run this code, I get NullPointerException saying that callAndroidList's parameter, list, is null. I haven't dealt much with JavaScript so I think it is possible that this is related to creation and removal of JavaScript object instances.
Could you help me out? Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这将创建一个对象,我认为你的意思是创建一个数组,所以也许应该是:
。
由于您创建的是具有数字属性的对象,而不是数组,因此它没有 slice 方法。将categoryTotals 初始化为数组应该可以解决这个问题。
顺便说一句,使用 slice 返回数组的副本似乎没有任何意义。既然categoryTotals不用于其他任何用途,为什么不直接返回它呢?
That will create an object, I think you mean to create an array, so perhaps it should be:
.
Since you are creating an object with numeric properties, not an array, it does not have a slice method. Initializing categoryTotals as an array should fix that.
Incidentally, there does not seem to be any point in using slice to return a copy of the array. Since categoryTotals is not used for anything else, why not just return it?