I want to call Java from Webview.
I have JavaScriptInterface below:
class JavaScriptInterface{
private Activity activity;
public JavaScriptInterface(Activity activiy) {
this.activity = activiy;
}
public void open(String message){
//do something
}
}
I add JavaScriptInterface
JavaScriptInterface jsInterface = new JavaScriptInterface(this);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(jsInterface, "JSInterface");
In my HTML, I have this onclick event:
onclick="window.JSInterface.open('hi');"
I also tried:
onclick="JSInterface.open('hi');"
I have this error in logcat:
04-16 14:55:15.829: W/dalvikvm(721): JNI WARNING: jarray 0x4050cf68 points to non-array object (Ljava/lang/String;)
04-16 14:55:15.829: I/dalvikvm(721): "WebViewCoreThread" prio=5 tid=9 NATIVE
04-16 14:55:15.829: I/dalvikvm(721): | group="main" sCount=0 dsCount=0 obj=0x40521218 self=0x1f6cf8
04-16 14:55:15.829: I/dalvikvm(721): | sysTid=729 nice=0 sched=0/0 cgrp=default handle=2059824
04-16 14:55:15.839: I/dalvikvm(721): | schedstat=( 5717972154 3300872155 567 )
04-16 14:55:15.839: I/dalvikvm(721): at android.webkit.WebViewCore.nativeTouchUp(Native Method)
04-16 14:55:15.839: I/dalvikvm(721): at android.webkit.WebViewCore.nativeTouchUp(Native Method)
04-16 14:55:15.839: I/dalvikvm(721): at android.webkit.WebViewCore.access$3300(WebViewCore.java:53)
04-16 14:55:15.839: I/dalvikvm(721): at android.webkit.WebViewCore$EventHub$1.handleMessage(WebViewCore.java:1158)
04-16 14:55:15.863: I/dalvikvm(721): at android.os.Handler.dispatchMessage(Handler.java:99)
04-16 14:55:15.869: I/dalvikvm(721): at android.os.Looper.loop(Looper.java:130)
04-16 14:55:15.869: I/dalvikvm(721): at android.webkit.WebViewCore$WebCoreThread.run(WebViewCore.java:629)
04-16 14:55:15.869: I/dalvikvm(721): at java.lang.Thread.run(Thread.java:1019)
04-16 14:55:15.869: E/dalvikvm(721): VM aborting
How to fix it? Or another way to do it?
Thanks
You need to enable Javascript in your WebView by setting
final WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.setVerticalScrollBarEnabled(false);
myWebView.setHorizontalScrollBarEnabled(false);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
You need to load your JS in your HTML DOM.
JsInterface jsInterface = new JsInterface();
jsInterface.wordDef = content;
myWebView.addJavascriptInterface(jsInterface, "interfaces");
myWebView.loadUrl("file:///android_asset/some.html");
Call your interface from HTML/JS
/**JAVA CODE **/
public class JsInterface {
public String someString;
Context mContext;
public void JsInterface(Context c){
mContext = c;
}
public String someFunction(){
Log.v("JSInterface", ""+someString);
return someString;
}
}
/* JS Code */
function addData(){
var data = interfaces.someFunction();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With