Android-logo

AndroidThe Best Guide to Create Android Charts in JavaScript

TutorialCreate & run your first Android charts application with LightningChart JS

Android Charts  

Here’s a new article I’m really excited about…this time, we will create an android charts data visualization application.

For this application, we will work with Android Studio and LightningChart JS (IIFE) but if you’re not familiar with android studio, in this article, you’ll walk step-by-step through the whole implementation for creating android charts apps.

Please notice:

I highly recommend installing all the tools mentioned in this article as in upcoming articles and tutorials, we will work with other frameworks like Ionic Capacitor, so they would be necessary to build mobile applications.

 Now, let’s begin.

Project Overview

Android-charts-mobile-view

LightningChart JS has a vast library of high-performance Android charts for JS.All of them can be featured in Android applications and for instance, you can see our LightningChart JS GitHub template to learn more.

Today, you’ll learn how to develop an app that runs on Android devices.

This application will feature three charts:

LightningChart JS has a vast library of high-performance Android charts for JS.

All of them can be featured in Android applications and for instance, you can see our LightningChart JS GitHub template to learn more.

Today, you’ll learn how to develop an app that runs on Android devices.

This application will feature three charts:

zip icon
Download the project to follow the tutorial

Setting Up Android Studio

Android Studio is a free IDE, so you will have the opportunity to work with it on Windows, macOS, and Linux. You can download Android Studio here

The installation is very easy, it’s a typical “next” window, but if you want to see the official Android documentation, you can get it from here. Finally, go to the SDK manager and install the latest platforms for android:

Android-SDK-manager

You can install all the platforms you need, but I recommend having the latest ones because it will be a requirement in case you want to publish your Android charts app in the Google Play console.

To finish setting up Android Studio, install the SDK Tools for Android. You can download the tools that I show or choose the tools you need.

Android-SDK-Tools

Java SDK

The next important thing is to install the latest Java SDK. For this installation, you will have to go to the official Oracle website. It would be necessary to create an account.

Gradle

Gradle is a build automation tool for multi-language software development. So, Gradle will be very important for mobile applications. You can get and see the installation documentation from here.

The Gradle installation is basically copying the source files to the specified paths.

Gradle is a build automation tool for multi-language software development.

So, Gradle will be very important for mobile applications. You can get and see the installation documentation from here.

The Gradle installation is basically copying the source files to the specified paths.

Environment Variables

It will be necessary to create the environment variables for Android Studio, Java SDK, and Gradle. You can go directly to the environment variables by typing those words in the windows menu:

It will be necessary to create the environment variables for Android Studio, Java SDK, and Gradle. 

You can go directly to the environment variables by typing those words in the windows menu:

Android Studio Environment Variables

Then, click on the [Environment Variables] button:

Environment Variables

Now you just need to add the variables with the path for the android SDK:

Variables Path Android SDK

Now, go to the System Variables section and edit the [Path] variable:

system Variables

Finally, just add the path for Java and the path for Gradle and proceed to code in Android Studio:

Java path Gradle path

Android Project

When you open the app folder in the android studio, you will see a tree like this one:

Android Studio File Tree

Now, let’s see the explanation of each folder and the relationships between the classes to the HTML files.

Manifests – AndroidManifest.xml

Every app project must have an AndroidManifest.xml file at the root of the project source set. The manifest file describes essential information about your app to the Android build tools, the Android operating system, and Google Play.

Every app project must have an AndroidManifest.xml file at the root of the project source set.

The manifest file describes essential information about your app to the Android build tools, the Android operating system, and Google Play.

<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".RenderingSpeedChart" android:exported="false"></activity>
        <activity android:name=".AudioSpectogramChart" android:exported="false"></activity>
        <activity android:name=".TradingChart" android:exported="false"></activity>
        <activity android:name=".MainActivity" android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

Inside the manifest, we need to specify the classes that will render a window inside our application. If you go to the java/lightningChart folder, you will see some files/classes with the same name that we have in the android manifest. 

Those names should match each class that we create and want to render. The manifest file is a very important file, in the future, you will use this file to specify many settings, for example, deep linking properties.

Inside the manifest, we need to specify the classes that will render a window inside our application. 

If you go to the java/lightningChart folder, you will see some files/classes with the same name that we have in the android manifest. 

Those names should match each class that we create and want to render. 

The manifest file is a very important file, in the future, you will use this file to specify many settings, for example, deep linking properties.

Java / LightningChart

java lightningchart android studio

Inside each file, we can create functions to validate, modify or create elements to be shown in the window. By default, you will find the [onCreate] function:

Inside each file, we can create functions to validate, modify or create elements to be shown in the window. 

By default, you will find the [onCreate] function:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_chart_display);
        final Bundle bundle = getIntent().getExtras();

        webView = findViewById(R.id.chartDisplayWebView);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.loadUrl("file:///android_asset/AudioSpectogramChart.html");
}

The [onCreate] method, will be called when the activity is created. In other words, when we click on a button that references a specific activity, the [onCreate] method will be called, inside this method we can load an HTML file (this file can work as a UI). Inside the [RenderingSpeedChart] file, you will see more code:

The [onCreate] method, will be called when the activity is created. 

In other words, when we click on a button that references a specific activity, the [onCreate] method will be called, inside this method we can load an HTML file (this file can work as a UI).

Inside the [RenderingSpeedChart] file, you will see more code:

class DataTask extends TimerTask {
        private WebView view;
        private Random random;

        DataTask(WebView view) {
            this.view = view;
            this.random = new Random();
        }

        @Override
public void run() {
            // Generate random float to show
            float f = random.nextFloat();
            final String data = Float.toString(f);
            // send the generated data to the WebView
            // method for sending depends on Android version
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
                view.post(new Runnable() {
                    @Override
                    public void run() {
                        view.evaluateJavascript("addData('" + data + "')", null);
                    }
                });
            } else {
                view.post(new Runnable() {
                    @Override
                    public void run() {
                        view.loadUrl("javascript:addData('" + data + "')");
                    }
                });
            }
        }
The [DataTask] class will be called by the [onCreate] method. This class will validate the current android version, and depending on the version, will choose the correct way to execute a javascript function.

 The [addData] function is located within the HTML file that is being loaded (file:///android_asset/RenderingSpeed.html). We are accessing the HTML as a “view” for this “controller”, using the Android [WebView] class:

 “WebView objects allow you to display web content as part of your activity layout but lack some of the features of fully developed browsers. A WebView is useful when you need to increase control over the UI and advanced configuration options that will allow you to embed web pages in a specially designed environment for your app.” Reference

The [DataTask] class will be called by the [onCreate] method. 

This class will validate the current android version, and depending on the version, will choose the correct way to execute a javascript function.

 The [addData] function is located within the HTML file that is being loaded (file:///android_asset/RenderingSpeed.html).

We are accessing the HTML as a “view” for this “controller”, using the Android [WebView] class:

 “WebView objects allow you to display web content as part of your activity layout but lack some of the features of fully developed browsers.

A WebView is useful when you need to increase control over the UI and advanced configuration options that will allow you to embed web pages in a specially designed environment for your app.” Reference

Java / LightningChart / MainActivity

The MainActivity will work as our [main()] method. This component is the first screen to appear when the user launches the app. From this file, we will declare the methods that will execute our activities. These methods can be executed by pressing a UI object:

The MainActivity will work as our [main()] method. This component is the first screen to appear when the user launches the app. 

From this file, we will declare the methods that will execute our activities.

These methods can be executed by pressing a UI object:

public void createRenderingSpeedChart(View view) {
        Intent intent = new Intent(this, RenderingSpeedChart.class);
        Bundle bundle = new Bundle();
        bundle.putBoolean("useRandom", true);
        intent.putExtras(bundle);
        startActivity(intent);
    }


    public void createAudioSpectogramChart(View view) {
        Intent intent = new Intent(this, AudioSpectogramChart.class);
        Bundle bundle = new Bundle();
        bundle.putBoolean("useRandom", true);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    public void createTradingChart(View view) {
        Intent intent = new Intent(this, TradingChart.class);
        Bundle bundle = new Bundle();
        bundle.putBoolean("useRandom", true);
        intent.putExtras(bundle);
        startActivity(intent);
}

Layout

When creating a new project, we will find some XML files inside the Layout folder:

Create new layout in Android Studio

The activity_main.xml will work as a default interface and it will be related to our MainActivity class. If you open the file, you will see a designer that contains the buttons for each chart:

The activity_main.xml will work as a default interface and it will be related to our MainActivity class. 

If you open the file, you will see a designer that contains the buttons for each chart:

Here you can add UI controls. If you click on each button, you will see the properties panel at the right of the window. In the [text] property, you can set the text to be displayed in the application.

In the [onClick] property, you can specify the name of the method that will call an activity. This method should be located in the MainActivity class.

Here you can add UI controls. If you click on each button, you will see the properties panel at the right of the window. 

In the [text] property, you can set the text to be displayed in the application.

In the [onClick] property, you can specify the name of the method that will call an activity.

This method should be located in the MainActivity class.

Android-Studio-Designer

Assets Folder

When creating a new project, we will find some XML files inside the Layout folder:

Andoid charts project assets folder

The activity_main.xml will work as a default interface and it will be related to our MainActivity class. If you open the file, you will see a designer that contains the buttons for each chart:

The activity_main.xml will work as a default interface and it will be related to our MainActivity class. 

If you open the file, you will see a designer that contains the buttons for each chart:

Android-Studio-Designer

In this folder, you will find the HTML files that will be loaded for the activities. Also, you will find a JSON file, that will contain the source data for the spectrogram chart.

The IIFE.js files contain all the functions and properties needed to create LC JS charts. In previous articles, we’ve already reviewed spectrograms and rendering charts. Feel free to check them out for more reference when working with Android charts.

In this folder, you will find the HTML files that will be loaded for the activities.

Also, you will find a JSON file, that will contain the source data for the spectrogram chart.

The IIFE.js files contain all the functions and properties needed to create LC JS charts.

In previous articles, we’ve already reviewed spectrograms and rendering charts.

Feel free to check them out for more reference when working with Android charts.

Audio Spectrogram Android Charts

Before reviewing the code, is worth saying that one of the charts we’ll use for Android data visualization applications will be the spectrograms. In this case, this spectrogram uses the LightningChart JS feature SurfaceScrollingGridSeries.

The way how a spectrogram under this feature works is by pushing new samples in while shifting old ones out. What a spectrogram does, is visualize audio, vibrancy, and other types of frequency spectrums. Using the LightningChart JS 2D & 3D Audio Spectrogram, users can deploy applications that measure, analyze, and process data in real time.

A real industry case scenario would implement this type of spectrogram charts in, for instance, a vibration analysis application. See the entire explanation of how to create a vibration charts app with TypeScript and LightningChart here.

Before reviewing the code, is worth saying that one of the charts we’ll use for Android data visualization applications will be the spectrograms.

In this case, this spectrogram uses the LightningChart JS feature SurfaceScrollingGridSeries.

The way how a spectrogram under this feature works is by pushing new samples in while shifting old ones out.

What a spectrogram does, is visualize audio, vibrancy, and other types of frequency spectrums.

Using the LightningChart JS 2D & 3D Audio Spectrogram, users can deploy applications that measure, analyze, and process data in real time.

A real industry case scenario would implement this type of spectrogram charts in, for instance, a vibration analysis application.

See the entire explanation of how to create a vibration charts app with TypeScript and LightningChart here.

LightningChart JS can work as embedded code, wrapped within script tags:

<body class="box">
<!-- Create div to render the chart into-->
<div id="target" class="row content"></div>

<!--IIFE assembly (lcjs.iife.js) is a standalone JS file,
  which does not need any build tools,
  such as NPM, to be installed-->
  
<!--Script source must be defined in it's own script tag-->
<script src="lcjs.iife.js"></script>


<!--Actual chart related script tag-->
<script>

	function setData(data){
		var arrData = data.split("||")
		const ArrX = JSON.parse(arrData[0])
		const ArrY = JSON.parse(arrData[1])
		const chartData = ArrX.map( ( itr1, itr2 ) => ( { x: itr1, y: ArrY[itr2] } ) )
		lineSeries.add(chartData)
	}

We’ll import the data in the following part of the code as shown:

// Load example data from file.
fetch(
    "https://lightningchart.com/lightningchart-js-interactive-examples/examples/assets/0913/audio2ch.json"
)

In case you need to load local data, you can replace the URL of the [audio2ch.json]file:

Replacing audio file Android charts application

When the activity loads the HTML, then all the JavaScript is executed and will create the chart object.

Rendering Speed Android Charts

The second chart we’ll create for our Android charts application is the Rendering Speed chart. Particularly, this is a LineSeries chart that measures time spans in milliseconds intervals. In this chart, we’re rendering 1 million data points.

The second chart we’ll create for our Android charts application is the Rendering Speed chart.

Particularly, this is a LineSeries chart that measures time spans in milliseconds intervals.

In this chart, we’re rendering 1 million data points.

Rendering-speed-chart

For this example, we’ll create the Speed Chart using the XY Chart type.

<script>
    let curX = 1;
	function addData(valueFromJava){
	    const value = Number(valueFromJava)
	    lineSeries.add({x: curX, y: value})
	    curX += 1
	}

    // Extract required parts from LightningChartJS.
    const {
        lightningChart
    } = lcjs //Note: @arction/lcjs is not needed here, when using IIFE assembly

    // Create a XY Chart.
    chart = lightningChart().ChartXY({
        // Set the chart into a div with id, 'target'.
        // Chart's size will automatically adjust to div's size.
        container: 'target'
    })
        .setTitle('My first chart') // Set chart title

    // Add a line series.
    const lineSeries = chart.addLineSeries()
        .setName('My data')
        .setStrokeStyle(s=>s.setThickness(2))

</script>

The chart will be created in the div “target”:

<script src="lcjs.iife.js"></script>
Using the function [addLineSeries], the lines will be added to the chart, using data points for X and Y, drawing a single line. See more in the documentationThe function [addData] will be called from the class [RenderingSpeedChart].

This class will be executed when the activity runs and will send random float numbers to the chart:

Using the function [addLineSeries], the lines will be added to the chart, using data points for X and Y, drawing a single line. See more in the documentation

The function [addData] will be called from the class [RenderingSpeedChart].

This class will be executed when the activity runs and will send random float numbers to the chart:

public void run() {
            // Generate random float to show
            float f = random.nextFloat();
            final String data = Float.toString(f);
            // send the generated data to the WebView
            // method for sending depends on Android version
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
                view.post(new Runnable() {
                    @Override
                    public void run() {
                        view.evaluateJavascript("addData('" + data + "')", null);
                    }
                });
            } else {
                view.post(new Runnable() {
                    @Override
                    public void run() {
                        view.loadUrl("javascript:addData('" + data + "')");
                    }
                });
            }
        }

Trading Candle Sticks Android Charts

A trading chart will be the last of the Android charts example we’ll include in the data visualization demo app. The chart fetches real-time data and features:

  • OHLC
  • Simple Moving Average
  • Exponential Moving Average
  • Bollinger Bands
  • Volume
  • Relative Strength Index

For this chart, we need to use the xydata.iife file. That file will contain the method [createOHLCGenerator] that creates OHCL data for OHCL charts. An OHLC chart shows the open, high, low, and close prices for a given period:

A trading chart will be the last of the Android charts example we’ll include in the data visualization demo app.

The chart fetches real-time data and features:

  • OHLC
  • Simple Moving Average
  • Exponential Moving Average
  • Bollinger Bands
  • Volume
  • Relative Strength Index

For this chart, we need to use the xydata.iife file. 

That file will contain the method [createOHLCGenerator] that creates OHCL data for OHCL charts.

An OHLC chart shows the open, high, low, and close prices for a given period:

Android-trading-chart

<script src="lcjs.iife.js"></script>
<script src="xydata.iife.js"></script>
<!--Actual chart related script tag-->
<script>


// Extract required parts from LightningChartJS.
const {
    lightningChart,
    AxisTickStrategies,
    OHLCFigures,
    emptyLine,
    AxisScrollStrategies,
    Themes
} = lcjs

// Import data-generator from 'xydata'-library.
const {
    createOHLCGenerator
} = xydata
Now the chart object is created. The look and feel are assigned by using the [theme] property. Other properties like the formatting and style of the axes are added by the function [setTickStrategy]:

Now the chart object is created. The look and feel are assigned by using the [theme] property. 

Other properties like the formatting and style of the axes are added by the function [setTickStrategy]:

// Create a XY Chart.
const chart = lightningChart().ChartXY({
    theme: Themes.darkGold,
})
// Use DateTime X-axis using with above defined origin.
chart
    .getDefaultAxisX()
    .setTickStrategy(
        AxisTickStrategies.DateTime,
        (tickStrategy) => tickStrategy.setDateOrigin(dateOrigin)
    )

chart.setTitle('Candlesticks Chart')
// Style AutoCursor using preset.
chart.setAutoCursor(cursor => {
    cursor.disposeTickMarkerY()
    cursor.setGridStrokeYStyle(emptyLine)
})
chart.setPadding({ right: 40 })

Other visual properties like padding, text title, and grid are set.

const dataSpan = 10 * 24 * 60 * 60 * 1000
const dataFrequency = 1000 * 60
createOHLCGenerator()
    .setNumberOfPoints(dataSpan / dataFrequency)
    .setDataFrequency(dataFrequency)
    .setStart(100)
    .generate()
    .toPromise()
    .then(data => {
        series.add(data)
    })

The data is created by performing a simple multiplication. We can assign random values for frequency and span data, but it depends on how big you need the chart.

For this chart, you will need the number of data points, Data Frequency (how long the time between two timestamps is), and the value where the data generation should start from.

The data is created by performing a simple multiplication.

We can assign random values for frequency and span data, but it depends on how big you need the chart.

For this chart, you will need the number of data points, Data Frequency (how long the time between two timestamps is), and the value where the data generation should start from.

Running the App

There are two ways to execute the application:

  1. Using an android emulator
  2. Connecting a real android device to the pc.

The android emulator could be the fastest option, but you will need to have enough RAM memory and Disk space.

To configure a virtual device, go to tools->Device Manager-> Create Device:

Android-emulator-setup

Then just select the device you need, download, and install it. But if you have an Android device, I recommend using it… emulators can slow down your computer and you won’t have all the capabilities to test. Also, some features may not work properly in the emulator. 

If you want to use a real device, you will have to activate the developer options on your phoneAfter that, connect your phone to your PC, and the Android Studio will set your device as a “Physical Device”. You can connect your physical phone to Android studio by selecting either of the options available in the drop-down list, e.g., using Wi-Fi:

Then just select the device you need, download, and install it.

But if you have an Android device, I recommend using it… emulators can slow down your computer and you won’t have all the capabilities to test. 

Also, some features may not work properly in the emulator. 

If you want to use a real device, you will have to activate the developer options on your phone

After that, connect your phone to your PC, and the Android Studio will set your device as a “Physical Device”. 

You can connect your physical phone to Android studio by selecting either of the options available in the drop-down list, e.g., using Wi-Fi:

Android-studio-pair-new-device

On your phone, go to Developer Options > Wireless Debugging > Pair Using QR/pairing code and search for “Wireless Debug”. From there, you can connect your phone over the Wi-Fi by pairing it with Android Studio using the QR code in Android studio or the pairing code.

Your Android Studio application project will launch on your phone just like any other app. Here is the final result. I’m using a Samsung device and as you can see, the android charting application runs smoothly.

On your phone, go to Developer Options > Wireless Debugging > Pair Using QR/pairing code and search for “Wireless Debug”.

From there, you can connect your phone over the Wi-Fi by pairing it with Android Studio using the QR code in Android studio or the pairing code.

Your Android Studio application project will launch on your phone just like any other app.

Here is the final result. I’m using a Samsung device and as you can see, the android charting application runs smoothly.

For additional information on Android charts with LightningChart JS, visit the GitHub repository

GitHub_logo
GitHub_logo

Conclusion

I think you should have realized that this project was more focused on Android configuration to be able to program and compile an application. I decided to do it this way since the most complicated thing about mobile development is having a configured environment that allows us to work correctly.

But you should have also realized that the implementation of Lightning Charts JS was much easier than configuring Android Studio. That is an important point.

Lightning Chart JS has been developed with great emphasis on compatibility and stability with different development environments. The JavaScript code did not have significant changes from the Node JS version… I literally copied and pasted the code… but… within the JAVA code, we saw some examples of how to interact with JavaScript and JAVA code, sending data to charts.

The behavior of android activities was also explained in a basic way. If you are a developer with little experience in Android, I hope this exercise has been able to guide you a little, I am very happy to share my experiences.

Goodbye and hope to see you in the next mobile development article.

I think you should have realized that this project was more focused on Android configuration to be able to program and compile an application. 

I decided to do it this way since the most complicated thing about mobile development is having a configured environment that allows us to work correctly.

But you should have also realized that the implementation of Lightning Charts JS was much easier than configuring Android Studio. That is an important point.

Lightning Chart JS has been developed with great emphasis on compatibility and stability with different development environments. 

The JavaScript code did not have significant changes from the Node JS version… I literally copied and pasted the code… but… within the JAVA code, we saw some examples of how to interact with JavaScript and JAVA code, sending data to charts.

The behavior of android activities was also explained in a basic way. 

If you are a developer with little experience in Android, I hope this exercise has been able to guide you a little, I am very happy to share my experiences.

Goodbye and hope to see you in the next mobile development article.

Omar Urbano

Omar Urbano

Software Engineer

LinkedIn icon
divider-light

Continue learning with LightningChart