Chevan
Chevan

Reputation: 60

How to pass a value/variable from an android java class to javascript/.html file in android 4.4.2 kitkat

I need to pass a value/variable (e.g. integer, string) from my java class to the .html file inside android assets. Let's say it is an integer value based on the user's click. I need to pass this integer to the .html file(scripts) so as to determine which ajax call is to be made (via an if-else loop). I googled everywhere but I couldn't find an answer to this.

I need to achieve this on android 4.4.2. Thanks in advance.

Upvotes: 2

Views: 5425

Answers (2)

Batman
Batman

Reputation: 129

Your Mainactivity.java may go like this

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

public class MainActivity extends Activity  {

    StringGetter stringGetter;
    String key;
    WebView webView;
    String url;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

      // Here The key value might be an integer or string 
      // I have used string

      key="sending values to javascript";


         url = "file:///android_asset/Index.html";
        webView =(WebView)findViewById(R.id.webView);
        webView.setWebViewClient(new MyBrowser());



        stringGetter = new StringGetter(this);

        webView.getSettings().setLoadsImagesAutomatically(true);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        webView.loadUrl(url);
        webView.addJavascriptInterface(new StringGetter(this), "AndroidFunction");



    }

    public class StringGetter {
        Context jContext;

        StringGetter(Context context){
            jContext = context;
        }
        @JavascriptInterface
        public String getString() {
            return key;

        }
    }



    private class MyBrowser extends WebViewClient {


        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }




    }


}
}

Your HTML file

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <title>Bootstrap 101 Template</title>

    <!-- Bootstrap -->
    <link href="css/bootstrap.min.css" rel="stylesheet">

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->


    <script type="text/javascript">

        function myMethod(){

        var tct = AndroidFunction.getString();
        document.getElementById("p").innerHTML = tct;
        alert(tct);
        }



    </script>
</head>
<body>
<nav class="navbar navbar-default navbar-fixed-top">

        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse" aria-expanded="false">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
        </button>

    <input type="button" id="btn" value=" Check " onClick="myMethod()"/>



    <a class="navbar-brand" href="#">Some Name </a>
    <div class="navbar-collapse collapse">
            <ul class="nav navbar-nav navbar-right">
                <li class="active"><a href = "#">Home</a></li>
                <li class="active"><a href = "#">About</a></li>
                <li class="active"><a href = "#">Downloads</a></li>
                <li class="active"><a href = "#">Contact</a></li>
                <li><div class="dropdown">
                    <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
                        Dropdown
                        <span class="caret"></span>
                    </button>
                    <ul class="dropdown-menu" aria-labelledby="dropdownMenu1">
                        <li><a href="#">Action</a></li>
                        <li><a href="#">Another action</a></li>
                        <li><a href="#">Something else here</a></li>
                        <li role="separator" class="divider"></li>
                        <li><a href="#">Separated link</a></li>
                    </ul>
                </div></li>
                </ul>
    </div>
</nav>

<div class="container">
    <div class="jumbotron text-center">
    <div class="container-fluid">

    <div class="row">
        <div class="col-md-3">ColUMN 1 contains some text and other components to work with </div>
        <div class="col-md-3">COLUMN 2 contains some text and other components to work with </div>
        <div class="col-md-3">ColUMN 3 contains some text and other components to work with </div>
        <p id="p">hello</p>
    </div>
</div>
    </div>
</div>

<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
</body>
</html>

Upvotes: 1

nikis
nikis

Reputation: 11244

Have you seen this http://developer.android.com/guide/webapps/webview.html? You are interested in Binding JavaScript code to Android code section. First declare interface, then implement the method that will return your integer. Then inside your JS code call this method to get the value.

EDIT

Interface for working with JS:

public class WebAppInterface {
    Context mContext;

    /** Instantiate the interface and set the context */
    WebAppInterface(Context c) {
        mContext = c;
    }

    /** Get the value */
    @JavascriptInterface
    public int getValue() {
        return value
    }
}

Add this interface to your WebView:

WebView webView = (WebView) findViewById(R.id.webview);
webView.addJavascriptInterface(new WebAppInterface(this), "Android");

Inside your JS code:

var value = Android.getValue();

Upvotes: 2

Related Questions