webview loads js graphic report

There are often some graphical report functions in projects. For the implementation of android graphical reports, you can use some open source android graphical report frameworks such as:
achartengine, hellocharts, MPAndroidChar, etc., although these frameworks are implemented very well, in actual projects the graphical reports we need are designed by designers. Maybe the effects we need are not provided by these frameworks, or the styles provided do not meet our needs. , at this time we need to modify these frameworks and change their styles. This requires us to be familiar with the source code of these frameworks and be able to modify them by applying inferences. However, it is simple to say, but it is not easy to actually modify it. Of course, we can also modify it ourselves. Defining views is implemented through drawing. This method is the most flexible, but it is not easy to draw a graphical control by yourself. So how can we quickly implement these graphical reports in the project? In fact, in There are often various graphical report functions in the development of web websites. There are many simple, easy-to-use, feature-rich graphical report frameworks for these. So why don’t we call these js graphical report frameworks through webview?

The following is an introduction to how to load a graphical report framework highcharts that I think is better through webview (for those who are unfamiliar with it, search for highcharts on Baidu):

First, let me introduce the effect I want to achieve: as shown below, I want to implement a report with the effect of a regional statistical chart.

First log in to highcharts (
http://www.hcharts.cn/demo/) Online demonstration platform, through this platform you can see that highcharts provides many graphic reports with effects. Find the effect we need: curve area chart

As shown in the picture above, the effect provided is very similar to the effect we need, but there are still some differences. Don’t worry, modify it now and learn how to use it while modifying it. As shown in the picture, click to edit the code.

QQ screenshot 20150914204139.png

As shown in the figure, the left side is the js code that controls the report effect. We mainly modify these codes. We may not be familiar with the method attributes of these js codes, but it doesn’t matter. We can try to modify the preview to understand what these attributes are used for. For similar graphical reports, we often pay attention to the implementation of x-axis, y-axis coordinate labels, data sets, etc. Reading the js code on the left, we find that only the series node sets numerical values. We might as well guess that we can modify the series node by , the value of data reaches the value corresponding to the y-axis of the modified area chart. As shown in the figure, I annotated and adjusted a data object, clicked “Run” and found that there was only one curve area chart. At the same time, I also found that the value corresponding to the modified data was indeed modified. The values of the key points of the area chart are known, and other attributes can also be learned through trial and error. Of course, this method allows people who do not understand highcharts to easily learn to integrate highcharts graphical reports. If you really want to learn highcharts, you still need to learn about it through the official API file. Usage of each attribute.

Okay, we already have a rough idea of what highcharts looks like. In an actual project, the data part must be dynamic, and the week on the abscissa may also be dynamic. So how do we do it?

HTML code: equalize the data on the left into variables. These variables are passed from the android code to js through the webview interface.

  1. <!doctype html>
    <html lang="en">
    <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <script type="text/javascript" src="http://cdn.hcharts.cn/jquery/jquery-1.8.3.min.js"></script>
      <script type="text/javascript" src="http://cdn.hcharts.cn/highcharts/highcharts.js"></script>
      <script type="text/javascript" src="http://cdn.hcharts.cn/highcharts/exporting.js"></script>
    <script type="text/javascript">
    var result = window.Android.getResult();//Call the method in android to obtain the data passed from android
    //alert("result=" + result);
    var jsonData = eval("(" + result + ")"); //Convert json string data to jsonObject object
    //alert("jsonData=" + jsonData);
    var xText = jsonData.xtext;//Parse xtext node data
    //alert("xText=" + xText);
    var data = jsonData.data;
    //alert("data=" + data);
    var xdata = jsonData.xdata;
    //alert("xdata=" + xdata);
    $(function () {
        $('#container').highcharts({
            chart: {
                type: 'areaspline'
            },
            title: {
                text: 'Charging Statistics'
            },
            legend: {
                layout: 'vertical',
                align: 'left',
                verticalAlign: 'top',
                x: 150,
                y: 100,
                floating: true,
                borderWidth: 1,
                backgroundColor: '#FFFFFF'
            },
            xAxis: {
             title: {
                    text: xText
                },
                categories:xdata,
                plotBands: [{ // visualize the weekend
                    from: 4.5,
                    to: 6.5,
                    //color: 'rgba(68, 170, 213, .2)'
                    color: 'rgba(68, 255, 0, 0)'
                }]
            },
            yAxis: {
                title: {
                    text: 'Charge'
                }
            },
            tooltip: {
                shared: true,
                valueSuffix: 'units'
            },
            credits: {
                enabled: false
            },
            plotOptions: {
                areaspline: {
                    fillOpacity: 0.5
                }
            },
            series: [{
                name: 'charge',
                data: data
            }]
        });
    });
      </script>
      <style>
        body{<!-- -->margin:0;padding:0;}
      </style>
    </head>
    <body>
      <div id="container" style="width:100%;height:400px"></div>
    </body>
    </html> 

Save the above code to an html file and copy it to the project assets directory:

The following code describes how to pass parameters to js through webview

java code

  1. private void initWebView() {
            activity = this;
            webview.setVisibility(View.VISIBLE);
            WebSettings webSettings = webview.getSettings();
            url = "file:/android_asset/index3.html";
            // Support JS
            webSettings.setJavaScriptEnabled(true);
            webSettings.setDisplayZoomControls(false); //Hide the webview zoom button
            webview.addJavascriptInterface(new JsInteration(),
                    "Android");
            webview.setWebChromeClient(new WebChromeClient() {
            });
            //Set progress bar
            webview.setWebChromeClient(new WebChromeClient() {
                public void onProgressChanged(WebView view, int progress) {
                    activity.setTitle("My brother is working hard to load...");
                    activity.setProgress(progress * 100);
                    if (progress == 100)
                        activity.setTitle(R.string.app_name);
                }
            });
            webview.setWebViewClient(new WebViewClient() {
                public void onReceivedError(WebView view, int errorCode,
                        String description, String failingUrl) { // Handle the error
                }
                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url2) {
                    if (Uri.parse(url2).getHost().equals(url)) {
                        // Load the site into the default browser
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri
                                .parse(url));
                        startActivity(intent);
                        return true;
                    }
                    // 1: Return false: Load url into the webview
                    // 2: Return true: Browser mode
                    return false;
                }
            });
            webview.loadUrl(url);
        }
        private String showtype;
        public class JsInteration {
            @JavascriptInterface
            public String getResult() {
                JSONObject jsonObject = new JSONObject();
                try {
                    JSONArray jsonArray1 = new JSONArray();
                    JSONArray jsonArray2 = new JSONArray();
                    for (int j = 0; j < list2.size(); j + + ) { //list2 here is a data collection obtained from the server through the interface
                        StatisticsChartInfo statisticsChartInfo = list2.get(j);
                        jsonArray1.put(statisticsChartInfo.getCurrtime());
                        jsonArray2.put(Double.valueOf(statisticsChartInfo
                                .getRevenue()));
                    }
                    jsonObject.put("xtext", xtext);
                    jsonObject.put("xdata", jsonArray1);
                    jsonObject.put("data", jsonArray2);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                LogUtil.d("Passed data=" + jsonObject.toString());
                return jsonObject.toString();
            }
        }
        @Override
        protected void onDestroy() {
            // TODO Auto-generated method stub
            super.onDestroy();
            if (webview!= null) {
                webview.destroy();
            }
        } 

Okay, so far, we understand how to simply load the js report framework through webview. Here we hope that more experts will point out the shortcomings, discuss and learn together, and make progress together.