Share this

Highcharts Android Wrapper Tutorial

bartosz gnacek Avatar

by

8 minutes read

 

In this tutorial, I will show you how to use Highcharts Android wrapper to create an interactive chart to display the UEFA champions data.
If you are an Android Developer, chances are Java is your language of choice. However, you may also have some favorite tools from other platforms, such as Highcharts, the most popular enterprise charting library for the web.

The Highcharts Android Wrapper offers you the capability to initialize the chart as a normal view in Android. This solution allows you to create a chart into a separate fragment or activity; you can also create a chart directly next to your other views without affecting them.
Ok, let’s get our hands dirty with a project to really experience the Highcharts Android Wrapper 🙂

Getting started

Create a new Project in Android Studio, name it, choose Android 5.0 and the Empty Activity template.

Add the Highcharts Android Framework to your project. There are two ways to do so. First, you can download the aar file and add it manually. Put the aar in the libs folder in your project structure. Then, add the following lines to the app build.gradle file:

repositories{
	flatDir{
		dirs ‘libs’
	}
}

And following in the dependencies:

compile (name: 'highcharts-release-v6.1', ext:'aar')

The second option is to add the library to the gradle dependencies like this:
Add the Highcharts repository to your build.gradle file:

repositories { 
    maven { 
        url "https://highsoft.bintray.com/Highcharts" 
    }
}

and following to the dependencies in your app build.gradle file:

dependencies {
    compile 'com.highsoft.highcharts:highcharts:6.1r'
}

Note, that if you plan to use the export module, you need to put this specific provider in your app:

<provider android:authorities="com.your.package.name.FileProvider"
   android:name="android.support.v4.content.FileProvider"
   android:exported="false"
   android:grantUriPermissions="true">
   <meta-data
       android:name="android.support.FILE_PROVIDER_PATHS"
       android:resource="@xml/provider_paths"/>
</provider>

And in add provider_paths file to xml folder containing this:

<?xml version="1.0" encoding="utf-8"?>
<paths>
   <files-path name="export" path="." />
</paths>

This completes the project setup, and you may now move on to creating your charts.

Creating chart to visualize team statistics using Highcharts

For this example, we will create a basic column chart to visualize some stats of the top 4 teams in the UEFA Champions League 2016/17.
At first, you need to create the proper layout in xml for your chart. To do this, go to your activity_main.xml and make sure the following lines are added:

<com.highsoft.highcharts.Core.HIChartView
   android:id="@+id/hc"
   android:layout_width="match_parent"
   android:layout_height="match_parent" />

After creating the layout, return back to MainActivity.java/code> where you create the chart. In the onCreate method you will create first the layout from xml resource and create a new instance of the HIChartView class, passing the context from that layout:

HIChartView chartView = (HIChartView) findViewById(R.id.hc);

Done!

Now let’s review the chart options. The HIOptions class is responsible for it. This one contains all the necessary information for data presentation and rendering the chart.
Create an instance of HIOptions class:

HIOptions options = new HIOptions();

Object of this class will be used to set up all needed options for the chart. It is worth noting that only a few of them are necessary to create the chart (for example series – which will be discussed later in this article). Let’s start by configuring the chart variable. To do this, we will need HIChart class:

HIChart chart = new HIChart();
chart.setType(“column”);
options.setChart(chart);

In the second line, the code above we have chosen the chart type by the type variable from the HIChart class. HIChart class offers much more, but in our example, this lone variable is sufficient. In the last line, we added chart to the options. It is a good practice to add everything to your options object at once to avoid missing some of them.
At this moment it is worth giving your chart a proper title:

HITitle title = new HITitle();

title.setText("UEFA Champions League 2016/17");
HISubtitle subtitle = new HISubtitle();
subtitle.setText(“Team statistics”);
options.setTitle(title);
options.setSubtitle(subtitle);

The title of the chart is managed by HITitle class, while HISubtitle is responsible for subtitle. After setting the title objects, we’re adding them to the options object.
It’s always a good idea to change the default axes names, to make it easier for others to interpret your dataset. Set the Axis titles as follows;

final HIYAxis hiyAxis = new HIYAxis();
hiyAxis.setMin(0);
hiyAxis.setTitle(new HITitle());
hiyAxis.getTitle().setText("Number");
options.setYAxis(new ArrayList(){{add(hiyAxis);}});

We want to display the data on a category xAxis. We set the categories as an ArrayList to the HIXaxis object and assign it to the xAxis object (HIXaxis) to the options object.

final HIXAxis hixAxis = new HIXAxis();
ArrayList categories = new ArrayList<>();
categories.add("Goals");
categories.add("Assists");
categories.add("Shots On Goal");
categories.add("Shots");

hixAxis.setCategories(categories);
options.setXAxis(new ArrayList(){{add(hixAxis);}});

Chart can have a few X and Y axes depending on needs, which is why it is added to options as ArrayList too.

Now, we will configure/set up the tooltip. Consider the following code:

HITooltip tooltip = new HITooltip();
tooltip.setHeaderFormat("<span style=\"font-size:15px\">{point.key}</span><table>");
tooltip.setPointFormat("<tr><td style=\"color:{series.color};padding:0\">{series.name}: </td>" + "<td style=\"padding:0\"><b>{point.y}</b></td></tr>");
tooltip.setFooterFormat("</talble>");
tooltip.setShared(true);
tooltip.setUseHTML(true);
options.tooltip = tooltip;

To manage tooltip you need to create a HITooltip class. Tooltip is a small widget which is visible by hovering over the chart, displaying the values of the datapoints. You have several series and line variables available for formatting the template of the tooltip. (All formatters variables are explained in the documentation).
In this article, it is worth noting that you must turn on the useHTML flag to let your tooltip use HTML formatting. Whereas the share flag lets you show one tooltip, but showing shared values whether the series you tap are from the same category or not.

At this moment, let’s add some chart type specific options:

HIPlotOptions plotOptions = new HIPlotOptions();
plotOptions.setColumn(new HIColumn());
plotOptions.getColumn().setPointPadding(0.2);
plotOptions.getColumn().setBorderWidth(0);
options.setPlotOptions(plotOptions);

In the above code, we added new HIPlotOptions class object. This object is designed to assign specific options to all series in the chart for a specific series type. In this case, the setter setColumn() is needed here because the plot options are applying to our column series. The pointPadding is adding padding space between each column and borderWidth sets the width of the border surrounding each column.

For now, we were talking only about options in our column chart. You may ask: where do we set the data in here exactly? Well, we will add them now!

HIColumn realMadrid = new HIColumn();
realMadrid.setName("Real Madrid");
ArrayList realMadridData = new ArrayList<>();
realMadridData.add(36);
realMadridData.add(31);
realMadridData.add(93);
realMadridData.add(236);
realMadrid.setData(realMadridData);

HIColumn juventus = new HIColumn();
juventus.setName("Juventus");
ArrayList juventusData = new ArrayList<>();
juventusData.add(22);
juventusData.add(10);
juventusData.add(66);
juventusData.add(178);
juventus.setData(juventusData);

HIColumn monaco = new HIColumn();
monaco.setName("Monaco");
ArrayList monacoData = new ArrayList<>();
monacoData.add(22);
monacoData.add(17);
monacoData.add(56);
monacoData.add(147);
monaco.setData(monacoData);

HIColumn atleticoMadrid = new HIColumn();
atleticoMadrid.setName("Atlético Madrid");
ArrayList atleticoMadridData = new ArrayList<>();
atleticoMadridData.add(15);
atleticoMadridData.add(9);
atleticoMadridData.add(55);
atleticoMadridData.add(160);
atleticoMadrid.setData(atleticoMadridData);

In the above long code snippet, you can see we instantiated four separate columns. Each of them contains data for the football clubs. Let’s talk about first one (the rest is done in the same way). At first, we created the HIColumn object which is responsible for column implementation. Next, we added the name for it and created another ArrayList holding the datapoints. At this moment, you are probably curious why we didn’t add any of those columns to options object yet. That’s because Columns are held by HISeries object. We need to add them to the series first! See here below;

ArrayList series = new ArrayList<>();
series.add(realMadrid);
series.add(juventus);
series.add(monaco);
series.add(atleticoMadrid);

options.setSeries(series);

Series is a special ArrayList containing HISeries objects. Each of chart type objects extends HISeries class, so we can add all our columns to the list without any trouble. In the last one, we add all columns as one ArrayList object to the options.

Now, when all settings are made, we can finish our work by assigning the configuration options to the chartView created at the beginning:

chartView.setOptions(options);

The result should look like this, congratulations!

Stay in touch

No spam, just good stuff

We're on discord. Join us for challenges, fun and whatever else we can think of
XSo MeXSo Me Dark
Linkedin So MeLinkedin So Me Dark
Facebook So MeFacebook So Me Dark
Github So MeGithub So Me Dark
Youtube So MeYoutube So Me Dark
Instagram So MeInstagram So Me Dark
Stackoverflow So MeStackoverflow So Me Dark
Discord So MeDiscord So Me Dark

Comments

  1. Linda

    |

    Great post!


  2. Tharmini

    |

    can we have all export options??


    1. Mustapha Mekhatria

      |

      Nice point. Please, feel free to add your request https://github.com/highcharts/highcharts/issues/new/choose


  3. Tharmini

    |

    Can we get that 9 export option on mobile app’s highcharts also??


    1. Mustapha Mekhatria

      |

      Same as above, just go here and add your request https://github.com/highcharts/highcharts/issues/new/choose
      Thanks for your input 🙂


  4. Tharmini

    |

    so for the moment we don’t have that function


    1. Tharmini

      |

      I got these errors, how to solve this any referrence
      2021-04-20 15:52:50.209 11013-11013/com.example.highcharts E/AndroidRuntime: FATAL EXCEPTION: main
      Process: com.example.highcharts, PID: 11013
      java.lang.IllegalArgumentException: Couldn’t find meta-data for provider with authority com.example.highcharts.FileProvider
      at androidx.core.content.FileProvider.parsePathStrategy(FileProvider.java:606)
      at androidx.core.content.FileProvider.getPathStrategy(FileProvider.java:579)
      at androidx.core.content.FileProvider.getUriForFile(FileProvider.java:417)
      at com.highsoft.highcharts.core.e.onDownloadStart(SourceFile:63)
      at ic.a(PG:548)
      at An.handleMessage(PG:25)
      at android.os.Handler.dispatchMessage(Handler.java:107)
      at android.os.Looper.loop(Looper.java:214)
      at android.app.ActivityThread.main(ActivityThread.java:7356)
      at java.lang.reflect.Method.invoke(Native Method)
      at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)


  5. Mustapha Mekhatria

    |

    Hi,
    Check the following link to solve your issue :
    https://github.com/highcharts/highcharts-android#export-module-requirements

    If you still have issues, feel free to get in touch with our tech support: https://github.com/highcharts/highcharts-android/issues


  6. Tharmini

    |

    Can we zoom into x-axis in mobile part?


  7. Mustapha Mekhatria

    |

    Hi,
    Yes, you can have the zoom capability on the xAxis:
    HIOptions options = new HIOptions();
    HIChart chart = new HIChart();
    chart.setZoomType("x");
    options.setChart(chart);

    Please, use the https://github.com/highcharts/highcharts-android/issues if you have more questions.


  8. Faisal Qayyum

    |

    How to redraw chart?


    1. Mustapha Mekhatria

      |

      Hi,
      Call redraw function on HIChartView; you can find more info about HIChartView: https://api.highcharts.com/android/highcharts/com/highsoft/highcharts/core/HIChartView.html.
      Feel free to check also the API: https://api.highcharts.com/android/highcharts/


  9. Igor

    |

    Hi
    Get error, how to fix?

    Could not HEAD ‘https://highsoft.bintray.com/Highcharts/com/highsoft/highcharts/highcharts/6.1r/highcharts-6.1r.pom’. Received status code 403 from server: Forbidden


  10. Yabaze T

    |

    Hi, Im trying to get scroll event of High chart in android platform. How can i achieve this?


    1. Rafał

      |

      Could you provide more info about your scroll? Did you mean “panning”? In Android, there is the “setOnScrollChangeListener” event, but it’s on the chartView so I don’t think yo’re looking for this.
      Maybe you’re looking for https://api.highcharts.com/highcharts/xAxis.events.afterSetExtremes


Leave a Reply to Yabaze T Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.