1

I have already seen a similar question in stackoverflow, but I want a better explained answer to this question. I am new to android development and I am trying to figure out how to pass a variable in my java code to the javascript in index.html. Any suggestions are welcomed.

2 Answers 2

0

You could try to use JsBridge library:

https://github.com/lzyzsd/JsBridge
Sign up to request clarification or add additional context in comments.

Comments

0

Try with the following code may be it will help you.

//Android WebView code
JavaScriptInterface JSInterface;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
wv = (WebView)findViewById(R.id.webView1);
wv.getSettings().setJavaScriptEnabled(true);
// register class containing methods to be exposed to JavaScript
JSInterface = new JavaScriptInterface();
wv.addJavascriptInterface(JSInterface, "JSInterface");
wv.loadUrl("file:///android_asset/myPage.html");
}

public class JavaScriptInterface {
@android.webkit.JavascriptInterface
public void showToast(String msg)
{
    Log.d("TAG",msg);
}
}



//This is your web page
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
       function init()
       {
          var testVal = 'Android Toast!’;
          Android.showToast(testVal);
       }
    </script>
</head>
<body>
<div style="clear: both;height: 3px;"> </div>
  <div>
  <input value="submit" type="button" name="submit"
       id="btnSubmit" onclick="javascript:return init();" />
</div>
 </body>
</html>

Comments

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.