Vicky
Vicky

Reputation: 941

how to call javascript function from Android

Now i am going on with to show bar chart in webview with help of below code showed the bar chart.

public class sample extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final WebView webview = (WebView)this.findViewById(R.id.webView);
        WebSettings webSettings = webview.getSettings();

        webSettings.setJavaScriptEnabled(true);  
        webSettings.setBuiltInZoomControls(true);
        webview.requestFocusFromTouch();

        webview.setWebChromeClient(new WebChromeClient());
        webview.setWebViewClient(new WebViewClient() 
        {

            public void onPageFinished(WebView view, String url)
            {
                  String str = "john";
              webview.loadUrl("javascript:callFromActivity('"+str+"')");

            }
        }
            );

        webview.loadUrl("file:///android_asset/mypage.html");
    }



}

Actually i need to pass certain values from Android to javaScript and show those value in chart (for eg: in bar chart i need to show the different user name in chart which i get those value from Android class to js). follwed link to pass value from Android to js: http://android-er.blogspot.in/2011/10/call-javascript-inside-webview-from.html

js file:

<html>

<script type="text/javascript" src="https://www.google.com/jsapi"></script>

<script>
var name=null;

function callFromActivity(s) {
 name = document.getElementById("mytext").innerHTML = s;
alert(name);

}


google.load('visualization', '1.1', {packages: ['corechart', 'bar']});

google.setOnLoadCallback(drawStacked);
function drawStacked() {

alert(name);
 console.log(name);
  var data = google.visualization.arrayToDataTable([
          ['USER', 'NAME', 'COUNT', 'POSITION'],
          ['USER1', name, 1, 1],
          ['USER2', name, 1, 2]


        ]);

      var options = {


  is3D: true, title: 'INVOICE',
        width: 1200,
        height: 240,
        legend: { position: 'top'},
        bar: { groupWidth: '50%' },
        isStacked: true,
      };

      var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
      chart.draw(data, options);

    }
</script>
<body >
<div id="chart_div"></div>
<p id="mytext">Hello!</p>
</body>
</html>

My Problem:

callFromActivity function gets the value but if i pass it to drawStacked it shows as undefiened.

How to solve this problem if there any alternative please help me out to solve this prob.

Upvotes: 0

Views: 355

Answers (1)

Spiros I. Economakis
Spiros I. Economakis

Reputation: 490

You register a JS interface into you webview. An example of a JS interface is this

    public class JsExampleInterface
    {

    private Context mContext;

    public JsExampleInterface(Context context)
    {
        this.mContext = context;
    }

    /**
     * Returns all the Device info
     * @return DeviceInfo object
     */
    @JavascriptInterface
    public String getDeviceInfo()
    {
        DeviceInfo deviceInfo = new DeviceInfo();
        deviceInfo.setSdk(Build.VERSION.SDK_INT);
        deviceInfo.setDevice(Build.DEVICE);
        deviceInfo.setModel(Build.MODEL);
        deviceInfo.setProduct(Build.PRODUCT);
        deviceInfo.setManufacturer(Build.MANUFACTURER);
        return mGson.toJson(deviceInfo);
    }
}

Then into your onCreate method you must register this interface like this

JsExampleInterface exampleInterface = new JsExampleInterface(this);
mWebView.addJavascriptInterface(exampleInterface, "ExampleInterface");

After that you will be able to use this js interface into the html like this:

// This returns a JSON object with all device info
ExampleInterface.getDeviceInfo()

Upvotes: 1

Related Questions