简体   繁体   中英

How to call a JavaScript function from java code android native

I need to load a HTML file which internally has some AJAX service calls. I need to call a function in that HTML file from Java code. I can see the data loading in web but not in Emulator.

My HTML file is below

 <!DOCTYPE html>
 <html>
<head>
<meta name="viewport" content="width=device-width, user-scalable=yes">
<link class="include" rel="stylesheet" type="text/css"
href="./jquery.jqplot.min.css" />
<link type="text/css" rel="stylesheet"
href="syntaxhighlighter/styles/shCoreDefault.min.css" />
<link type="text/css" rel="stylesheet"
href="syntaxhighlighter/styles/shThemejqPlot.min.css" />

<script class="include" type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<script class="include" type="text/javascript"
    src="./jquery.jqplot.min.js"></script>
<script type="text/javascript"
    src="syntaxhighlighter/scripts/shCore.min.js"></script>
<script type="text/javascript"
    src="syntaxhighlighter/scripts/shBrushJScript.min.js"></script>
<script type="text/javascript"
    src="syntaxhighlighter/scripts/shBrushXml.min.js"></script>
<!-- End Don't touch this! -->

<!-- Additional plugins go here -->

<script class="include" language="javascript" type="text/javascript"
    src="./plugins/jqplot.dateAxisRenderer.min.js"></script>
<script class="include" language="javascript" type="text/javascript"
    src="./plugins/jqplot.ohlcRenderer.min.js"></script>
<script class="include" language="javascript" type="text/javascript"
    src="./plugins/jqplot.highlighter.min.js"></script>
    <script type="text/javascript" src="./plugins/jqplot.dateAxisRenderer.min.js"></script>
    <script type="text/javascript" src="./plugins/jqplot.canvasTextRenderer.min.js"></script>
    <script type="text/javascript" src="./plugins/jqplot.canvasAxisTickRenderer.min.js"></script>
    <script type="text/javascript" src="./plugins/jqplot.categoryAxisRenderer.min.js"></script>
    <script type="text/javascript" src="./plugins/jqplot.barRenderer.min.js"></script>
    <script type="text/javascript" src="./plugins/jqplot.cursor.min.js"></script>       
<script class="code" language="javascript" type="text/javascript">
    var arr = [];
    var arr1 = [];
        var jsonstr;
        $(document).ready(function() {
              $.jqplot.config.enablePlugins = true;
              $("#status").html("Loading...");
              $("#status").animate({opacity: 1,top: "200px"},200);
        });
    function getData(symbolId,timeLine,type){
        //$("#mydiv").html(symbolId +" "+timeLine+" "+type);

        $.ajax({
              url: 'http://83.101.141.1:8020/mTadawul/TadawulService.svc/GetOHLCData?Symbol='+symbolId+'&Char='+timeLine,
              dataType: 'json',
              async: false,
              success: function(data) {
                  jsonstr = jsontoarray(eval (data));
                  /*Custom Code to check the data*/
                  if(data != "")
                  {$("#status").animate({opacity: 0,top: "-50px"},200);createChart(type, timeLine);}else{$("#status").html("No Data");$("#status").animate({opacity: 1,top: "200px"},200);}

                }
        });
        //$.getJSON('http://183.82.0.37:8080/TadawulWCFService/TadawulService.svc/GetOHLCData?Symbol=1010&Char='+timeLine, function(data) {


        //});
        return 1;
    }

    function jsontoarray(jsonstr){
    var arrayl = [];
        for (var i = 0; i < jsonstr.length; i++) { 
            var values = new Array();
            values[0] = jsonstr[i].TimeStamp.replace("T"," ").replace("nm","");
            values[1] = jsonstr[i].Open;
            values[2] = jsonstr[i].High;
            values[3] = jsonstr[i].Low;
            values[4] = jsonstr[i].Close;
            arrayl.push(values);

        }
        return arrayl;
    }
    function createChart(type, timeLine) {
        timeLine = typeof timeLine !== 'undefined' ? timeLine : 'M';
        console.log(jsonstr);
        var charts = [{
name: "chart2",
seriesDefaults: {
    yaxis: 'y2axis'
},
axes: {
    xaxis: {
        renderer: $.jqplot.DateAxisRenderer,
        numberTicks:36,
        tickOptions: {
            formatString: '%b %e %Y ',
       angle:-90
        }, 
        tickRenderer:$.jqplot.CanvasAxisTickRenderer,
         labelOptions:{
        fontFamily:'Arial',
        fontSize: '14pt'
      },
      labelRenderer: $.jqplot.CanvasAxisLabelRenderer
    },

},  
series: [{
    renderer: $.jqplot.OHLCRenderer,
    rendererOptions: {
        candleStick: true
    }
}],
highlighter: {
    show: true,
    showMarker: true,
    tooltipAxes: 'xy',
    yvalues: 4,
    formatString: '<table class="jqplot-highlighter"> \<tr><td>date:</td><td>%s</td></tr> \<tr><td>open:</td><td>%s</td></tr> \<tr><td>high:</td><td>%s</td></tr> \<tr><td>low:</td><td>%s</td></tr> \<tr><td>close:</td><td>%s</td></tr></table>'
},

data: [jsonstr]

}];
        if(type == "line"){
            charts[0].series[0]={};
        }
        else if(type == "bar"){
            charts[0].series[0].rendererOptions = {smooth : true};
        }else
        {
            charts[0].series[0].rendererOptions = {candleStick : true};
        }
        if(timeLine == 'H'){
            charts[0].axes.xaxis.tickOptions = { formatString: '%b %e %#I %p',
                       angle:-90};
            //charts[0].axes.xaxis['tickInterval'] =  "1 hour";
        }
        $('#chart2').jqplot(charts[0]);



    }

</script>

<div id="mydiv"></div>
<label id="lbl"></label>

<div class="test" style="position:absolute; top:-50px; left:40%; color:#333333; opacity:0;z-index:9999;" id="status">No Data</div>
<div id="chart2" style="height: 400px; width: 720px;">

</div>

In that code I need to call getData() passing 3 parameters from Java code.

My Java code is below:

webView.addJavascriptInterface(new JavaScriptInterface(this), "Android");

String loc = "file:///android_asset/candlechart/candlebar.html";
    webView.getSettings().setJavaScriptEnabled(true);
    webView.clearView();
    // myWebView.measure(100, 100);
    webView.getSettings().setUseWideViewPort(true);
    webView.getSettings().setLoadWithOverviewMode(true);
    webView.loadUrl(loc);
    webView.loadUrl("javascript:getData('1020','M','bar')");

    webView.setWebViewClient(new WebViewClient() {
        public void onPageFinished(WebView view, String loc) {

        }

    }); 

You are calling your second loadUrl() way too soon. loadUrl() is asynchronous. You need to wait until your page is loaded. Call webView.loadUrl("javascript:getData('1020','M','bar')"); in the OnPageFinished method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM