Tuesday, 19 February 2019

Display Google Charts (pie chart) on Android WebView

http://android-er.blogspot.com/2014/08/display-google-charts-pie-chart-on.html


This example show how to use Google Charts to display pie chart on Android WebView. Google chart tools are powerful, simple to use, and free. It not only display a static graphic, but also provide user touch interactive operation, check the video on the bottom.

Display Google Charts (pie chart) displayed Android WebView
We have a MainActivity to collect data from user:
package com.example.androidwebchart;

import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;


public class MainActivity extends ActionBarActivity {
 
 EditText num1, num2, num3, num4, num5;
 Button btnShow;

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

        num1 = (EditText)findViewById(R.id.num1);
        num2 = (EditText)findViewById(R.id.num2);
        num3 = (EditText)findViewById(R.id.num3);
        num4 = (EditText)findViewById(R.id.num4);
        num5 = (EditText)findViewById(R.id.num5);
        btnShow = (Button)findViewById(R.id.show);
        
        btnShow.setOnClickListener(btnShowOnClickListener);
    }
    
    OnClickListener btnShowOnClickListener =
     new OnClickListener(){

   @Override
   public void onClick(View v) {
    Intent intent = new Intent(
     MainActivity.this, 
     ShowWebChartActivity.class);
    
    intent.putExtra("NUM1", getNum(num1));
    intent.putExtra("NUM2", getNum(num2));
    intent.putExtra("NUM3", getNum(num3));
    intent.putExtra("NUM4", getNum(num4));
    intent.putExtra("NUM5", getNum(num5));

    startActivity(intent);
   }
     
    };
    
    private int getNum(EditText editText){
     
     int num = 0;

     String stringNum = editText.getText().toString();
     if(!stringNum.equals("")){
      num = Integer.valueOf(stringNum);
     }
     
     return (num);
    }

}

/res/layout/activity_main.xml, layout of MainActivity.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context="com.example.androidwebchart.MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:autoLink="web"
        android:text="http://android-er.blogspot.com/"
        android:textStyle="bold" />
    <EditText
        android:id="@+id/num1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="number"/>
    <EditText
        android:id="@+id/num2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="number"/>
    <EditText
        android:id="@+id/num3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="number"/>
    <EditText
        android:id="@+id/num4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="number"/>
    <EditText
        android:id="@+id/num5"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="number"/>
    <Button
        android:id="@+id/show"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Show Chart"/>

</LinearLayout>

When User click on the "Show Chart" button, it will start another activity, ShowWebChartActivity.java, and pass user data. ShowWebChartActivity load a WebView with our HTML to display Google Charts with Javascript. We have to implement WebAppInterface, with methods of @JavascriptInterface, getNum1()...getNum5(). It will be called by Javascript inside HTML to retrieve user data.
package com.example.androidwebchart;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;

@SuppressLint("SetJavaScriptEnabled") 
public class ShowWebChartActivity extends ActionBarActivity {
 
 WebView webView;
 int num1, num2, num3, num4, num5;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_webchart);
        
        Intent intent = getIntent();
        num1 = intent.getIntExtra("NUM1", 0);
        num2 = intent.getIntExtra("NUM2", 0);
        num3 = intent.getIntExtra("NUM3", 0);
        num4 = intent.getIntExtra("NUM4", 0);
        num5 = intent.getIntExtra("NUM5", 0);
        
        webView = (WebView)findViewById(R.id.web);
        webView.addJavascriptInterface(new WebAppInterface(), "Android");

        webView.getSettings().setJavaScriptEnabled(true); 
        webView.loadUrl("file:///android_asset/chart.html");
 }

 public class WebAppInterface {

     @JavascriptInterface
  public int getNum1() {
   return num1;
  }
  
  @JavascriptInterface
  public int getNum2() {
   return num2;
  }
  
  @JavascriptInterface
  public int getNum3() {
   return num3;
  }
  
  @JavascriptInterface
  public int getNum4() {
   return num4;
  }
  
  @JavascriptInterface
  public int getNum5() {
   return num5;
  }
 }

}

/res/layout/layout_webchart.xml, layout of ShowWebChartActivity.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:autoLink="web"
        android:text="http://android-er.blogspot.com/"
        android:textStyle="bold" />
    
    <WebView
        android:id="@+id/web"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</LinearLayout>

/assets/chart.html, our HTML to load and display Google Charts. Actually it is modified from Google Quick Start example of pie chart. The main difference is it retrieve user data by calling Android JavascriptInterface methods (getNum1()...getNum5()), instead of fixed data.
<html>
  <head>
    <!--Load the AJAX API-->
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
    
      // Load the Visualization API and the piechart package.
      google.load('visualization', '1.0', {'packages':['corechart']});
      
      // Set a callback to run when the Google Visualization API is loaded.
      google.setOnLoadCallback(drawChart);


      // Callback that creates and populates a data table, 
      // instantiates the pie chart, passes in the data and
      // draws it.
      function drawChart() {

      // Create the data table.
      var data = new google.visualization.DataTable();
      data.addColumn('string', 'ITEM');
      data.addColumn('number', 'VALUE');
      data.addRows([
        ['Item 1', Android.getNum1()],
        ['Item 2', Android.getNum2()],
        ['Item 3', Android.getNum3()], 
        ['Item 4', Android.getNum4()],
        ['Item 5', Android.getNum5()]
      ]);

      // Set chart options
      var options = {'title':'Android-er: Load Google Charts (pie chart) with WebView',
                     'width':600,
                     'height':600};

      // Instantiate and draw our chart, passing in some options.
      var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
      chart.draw(data, options);
    }
    </script>
  </head>

  <body>
 <!--Div that will hold the pie chart-->
    <div id="chart_div" style="width:600; height:600"></div>
  </body>
</html>

Finally, modify AndroidManifest.xml to add <activity> of ShowWebChartActivity, and <uses-permission> of "android.permission.INTERNET".
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.androidwebchart"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".ShowWebChartActivity"
            android:label="@string/app_name" >
        </activity>
    </application>

</manifest>


download filesDownload the files.

More Google Charts examples on Android WebView
Capture image generated by Google Charts API
Display Donut Chart on Android WebView, using Google Charts

Google Charts


Quick Start

Here's a simple example of a page that displays a pie chart:

You can copy the snippet below to an .html file on your computer and open it in your browser to display the pie chart shown above:
<html>   <head>     <!--Load the AJAX API-->     <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>     <script type="text/javascript">       // Load the Visualization API and the corechart package.       google.charts.load('current', {'packages':['corechart']});       // Set a callback to run when the Google Visualization API is loaded.       google.charts.setOnLoadCallback(drawChart);       // Callback that creates and populates a data table,       // instantiates the pie chart, passes in the data and       // draws it.       function drawChart() {         // Create the data table.         var data = new google.visualization.DataTable();         data.addColumn('string', 'Topping');         data.addColumn('number', 'Slices');         data.addRows([           ['Mushrooms', 3],           ['Onions', 1],           ['Olives', 1],           ['Zucchini', 1],           ['Pepperoni', 2]         ]);         // Set chart options         var options = {'title':'How Much Pizza I Ate Last Night',                        'width':400,                        'height':300};         // Instantiate and draw our chart, passing in some options.         var chart = new google.visualization.PieChart(document.getElementById('chart_div'));         chart.draw(data, options);       }     </script>   </head>   <body>     <!--Div that will hold the pie chart-->     <div id="chart_div"></div>   </body> </html>

How About a Bar Chart?

Convert the pie chart to a bar chart by replacing
google.visualization.PieChart with
google.visualization.BarChart
in the code and reloading your browser. You may notice that the "Slices" legend is truncated. To fix this, change width to 500 from 400, save the file, and reload your browser.