2

i am trying to call a java method in androind activity from html button, loaded in webView but when i click the buton nothing happens. Here is the code i have tried

Here is the html code

 <button onClick="activity.TestMethod();">Call Java Activity Method</button>

Here is the android activity method

public void TestMethod()
  {
     Toast.makeText(getApplicationContext(), "this is my Toast message!!! =)",
     Toast.LENGTH_LONG).show(); 

  }

I have enabled JavaScript by using

 WebView index = (WebView) findViewById(R.id.webView1);
 WebSettings webSettings = index.getSettings(); 
 webSettings.setJavaScriptEnabled(true);
 index.loadUrl("file:///android_asset/index.html");
AddyProg
  • 2,960
  • 13
  • 59
  • 110

2 Answers2

4

Activity.java File

final MyJavaScriptInterface myJavaScriptInterface = new MyJavaScriptInterface(
                    this);
            webView.addJavascriptInterface(myJavaScriptInterface, "activity");

public class MyJavaScriptInterface {
        Context mContext;

    MyJavaScriptInterface(Context c) {
        mContext = c;
    }

    //Add @JavascriptInterface to call this method from > 4.2 Android Version
    @JavascriptInterface
    public void TestMethod() {

        Toast.makeText(mContext, "Hello from JavaScript Interface", Toast.LENGTH_SHORT).show(); 
    }
}

HTML File

 <button onClick="jsMethod();">Call Java Activity Method</button>

<script type="text/javascript">
   function jsMethod(){
       activity.TestMethod();
    }
</script>
Harsh Goswami
  • 502
  • 3
  • 12
0

You have to set up a JavaScriptInterface for the WebView first. See here for an example.

Community
  • 1
  • 1
Gabriel Negut
  • 13,860
  • 4
  • 38
  • 45