Reputation: 13
hello i am trying for few days in few ways to get this working and i failed if someone can please help me find out what i'm doing wrong, all i want is that when i press the button it will show the javascript text in Toast:
my java main:
package com.callphone;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String content = "file:///android_asset/www/mypage.html";
WebView webView = (WebView) findViewById(R.id.mybrowser);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient());
webView.loadUrl(content);
webView.addJavascriptInterface(new MyJavaScriptInterface(this), "AndroidFunction");
}
public class MyJavaScriptInterface {
Context mContext;
MyJavaScriptInterface(Context c) {
mContext = c;
}
public void showToast(String toast){
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
}
}
my xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<WebView
android:id="@+id/mybrowser"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>
my html:
<!DOCTYPE html>
<html>
<head>
<script src="index.js"></script>
</head>
<body>
<h1>What's your number</h1>
<button onclick="shownumber('55555')">show number</button>
</body>
</html>
and my javascript:
function shownumber(number) {
AndroidFunction.showToast(number);
}
when i change the javascript to alert it display the alert, so i figure the problem with the AndroidFunction
thanks in advance.
Upvotes: 1
Views: 338
Reputation: 720
According to the doucmentation you are missing the annotation @JavascriptInterface in your MyJavaScriptInterface
This should work:
public class MyJavaScriptInterface {
Context mContext;
MyJavaScriptInterface(Context c) {
mContext = c;
}
@JavascriptInterface
public void showToast(String toast){
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
}
Upvotes: 1