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");

2 Answers 2

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>
Sign up to request clarification or add additional context in comments.

1 Comment

its giving syntax error in line 3 on "actvitiy" , it says " VariableDeclarator expected "
0

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

1 Comment

i have already done that please check the update in question. . .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.