Just Simple Info

Pages

Android Calling Javascript function from Java function and Javascript function to Java function in Webview.

Good day coders..

I will share a simple code snippet on how to call Javascript function from android Java function and
Javascript function to android Java function in webview.

Actually it is easy to implement this such function. I think the hardest thing in this is, It's hard to debug. If you have error in javascript the logcat will not show any error it will not just worked.
So, you have to guess what is/are the possible error in the code.



The project structure is simple.
It have a html file in asset with two java class file.

Here is the html file.


<html>
<head>
<script type="text/javascript">
 
 function clickEvent(){
  
  window.JavaAndJavascriptBridge.showData("I'm from javascript");
 
  
 }
 
 function callFromJava(data){
  
  document.getElementById('label').innerHTML = data;
  
 }
</script>
</head>
<body>
<button onClick="clickEvent()">Html Btn.. Click Me!</button>
<br/>
<label id="label"></label>
</body>
</html>


Here is the CustomWebview class file.


public class CustomWebview  extends WebView{

 MainActivity mainActivity;
 
 
 @SuppressLint("SetJavaScriptEnabled") 
 public CustomWebview(MainActivity mainActivity) {
  super(mainActivity);
  this.mainActivity = mainActivity;
  
  WebSettings webSettings = this.getSettings();
  webSettings.setJavaScriptEnabled(true);
  /**
   * the important
   */
  this.addJavascriptInterface(new JavaAndJavascriptBridge(),"JavaAndJavascriptBridge");
  
  this.loadUrl("file:///android_asset/TestHtml.html");
  
  
 }
 
 int x = 0;
 /**
  * 
  * @author la
  *
  */
  public class JavaAndJavascriptBridge{
   
   public void showData(final String dataFromJavascript){
    
   
    
   mainActivity.textView.postDelayed(new Runnable() {
    
    @Override
    public void run() {
     // TODO Auto-generated method stub
     
      mainActivity.textView.setText(dataFromJavascript+" "+x);
      Log.e("data",dataFromJavascript+"..");
      x++;
    }
   }, 100);
   
    
    Toast.makeText(mainActivity, dataFromJavascript, Toast.LENGTH_SHORT).show();
    
   }
  }
}

If your targetSdkVersion >= 17 replace JavaAndJavascriptBridge by below code.


public class JavaAndJavascriptBridge{
  
  @JavascriptInterface
  public void showData(final String dataFromJavascript){
   
  mainActivity.textView.postDelayed(new Runnable() {
  @Override
  public void run() {
  // TODO Auto-generated method stub
    
   mainActivity.textView.setText(dataFromJavascript+" "+x);
   Log.e("data",dataFromJavascript+"..");
   x++;
   }
  }, 100);
  
   
   Toast.makeText(mainActivity, dataFromJavascript, Toast.LENGTH_SHORT).show(          );
   
  }
}

That's it.
Hope it helped..
Happy coding.

Download source code here.

No comments:

Post a Comment