I know this has been already asked here.
But even after following the accepted answer here (and similar other questions on SO) - I am unable to link my client side Android code to my JavaScript due to the Uncaught ReferenceError.
My Android code snippet -
public class WebActivityExample extends Activity {
WebView mWebView;
WebAppInterface WAInterface;
@Override
public void onCreate(Bundle savedInstanceState) {
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
WAInterface = new WebAppInterface(this);
mWebView.addJavascriptInterface(WAInterface, "Android");
mWebView.loadUrl("http://myurlhere");
}
public class WebAppInterface {
Context mContext;
/** Instantiate the interface and set the context */
WebAppInterface(Context c) {
mContext = c;
}
/** Show a toast from the web page */
@JavascriptInterface
public void showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
System.out.println("toast " + toast);
}
}
}
My website is running AngularJS on the client side and PHP on the server side. Hence I have a index.php
file that holds all my JavaScript files as well as my CSS files that need to be included for the entire application.
This is my HTML code -
(It is an Angular template view that includes the HTML button) -
<input type ="button" value="Say Hello!" onClick="showAndroidToast('Hello Android!')" />
This is my index.php file that holds all the JS/CSS files -
<html xmlns:ng="http://angularjs.org" id="ng-app" ng-app="myapp">
<head>
(various scripts and stylesheets included here)
</head>
<body>
....
....
<script type="text/javascript">
function showAndroidToast(toast) {
alert(toast);
Android.showToast(toast);
}
</script>
</body>
</html>
The onClick is definitely calling the showAndroidToast function since the alert pops up the message 'Hello Android' - but I am just not able to link it to the Android function 'showToast'. I've followed the docs on Android and various answers on Stackoverflow and have done exactly the same thing as asked - but still end up getting the Uncaught Reference error! What am I missing out on/ or doing wrong????
This is how the logcat error looks -
I/chromium: [INFO:CONSOLE(243)] "Uncaught ReferenceError: Android is not defined", source: ..
Update 1 :
After referring the following SO answers : 1. Can a java file have more than one class? 2. Android 4.2.1, WebView and javascript interface breaks
I created a new Java class called WebAppInterface and shifted the public class from this code snippet (within my main class) into the WebAppInterface.java class.
I also changed my Minimum APK version to 17.
Still facing the same issue. Any help would be appreciated.