Using Charts in Android Java

In this tutorial, we will write code to use MPAndroidChart library in Android application using Java.
You can use any latest version of Android Studio. This tutorial was written using Android Studio 4.1.

Using Charts in Android Java App

Charts provide quite good visualization for the users but what’s the point of knowing all that when we don’t know how to integrate them.
So, here’s a quick tutorial about using charts in the native Android java app.
Obviously, first create a new project with min SDK version as 26 or directly write this code inside the app you are already working on.
Now proceeding to the code section.

Code

Since we are using opensource library so add these dependencies in your gradle files:
(These 2 changes belong to two different files.)

repositories {
    maven { url 'https://jitpack.io' }
}

dependencies {
    implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0'
}

Now we create a PieChart instance in activity_main.xml file:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.453"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.084" />

    <com.github.mikephil.charting.charts.PieChart
        android:id="@+id/progressChart"
        android:layout_width="355dp"
        android:layout_height="285dp"
        android:layout_marginBottom="268dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <Button
        android:id="@+id/increment_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="96dp"
        android:text="increment button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Now we make button and use onClick() function to update chart data and also to make chart look good we do some minor modifications to the chart properties.

So, write this code in MainActivity.java File:

package org.codespeedy;

import android.graphics.Color;
import android.os.Bundle;
import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;

import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.utils.ColorTemplate;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    Button mIncrementButton;
    private PieChart pieChart;

    int count = 0;
    int target = 100;

    @Override
    public void onCreate(Bundle saved) {
        super.onCreate(saved);
        setContentView(R.layout.activity_main);

        mIncrementButton = findViewById(R.id.increment_button);
        pieChart = findViewById(R.id.progressChart);

        setupPiechart();

        mIncrementButton.setOnClickListener(v->{
            if(count<target)
            {
                count++;
                RefreshDataSet(count,target);
            }
        });
        RefreshDataSet(count,target);
    }

    private void setupPiechart() {
        Description description = new Description();
        description.setText("");
        pieChart.setDescription(description);
        pieChart.setRotationEnabled(true);
        pieChart.setHoleRadius(35f);
        pieChart.setTransparentCircleAlpha(0);
        pieChart.setCenterText("Step Tracker");
        pieChart.setCenterTextSize(13);

    }

    private void RefreshDataSet(long steps, long target) {

        ArrayList<PieEntry> yEntrys = new ArrayList<>();
        
        yEntrys.add(new PieEntry(steps, "Total Steps Taken"));
        yEntrys.add(new PieEntry((target - steps > 0 ? target - steps : 0f), "Remaining Steps"));

        //create the data set
        PieDataSet pieDataSet = new PieDataSet(yEntrys, "");
        pieDataSet.setSliceSpace(1);
        pieDataSet.setValueTextSize(20);
        pieDataSet.setValueTextColor(Color.rgb(255, 255, 255));

        //add colors to dataset
        ArrayList<Integer> colors = new ArrayList<>();
        colors.add(ColorTemplate.getHoloBlue());
        colors.add(Color.BLUE);
        pieDataSet.setColors(colors);

        //add legend to chart
        Legend legend = pieChart.getLegend();
        legend.setForm(Legend.LegendForm.CIRCLE);
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);
        legend.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        legend.setDrawInside(false);

        //create pie data object
        PieData pieData = new PieData(pieDataSet);
        pieChart.setData(pieData);
        pieChart.invalidate();
    }

}

In the above code:
setupPiechart() function is called to setup stuff like description, hole-radius, center text etc.
ThenĀ  we created RefreshDataSet() function to refresh the data of the PieChart.

In the RefreshDataSet() function:
PieEntry is sort of datatype used by the PieChart.
PieEntry(steps, “Total Steps Taken”) -> steps is the value and “Total Steps Taken” is the display text on chart.
After creating multiple entries in the yEntrys array, finally a PieDataSet object is created which contains all the data that will be plotted.
Then, we set the new data into out PieChart using the following lines:

PieData pieData = new PieData(pieDataSet); 
pieChart.setData(pieData); 
pieChart.invalidate();

Note that it is necessary to call pieChart.invalidate(); otherwise the dataset given to PieChart won’t refresh.

Now connect your mobile to laptop using USB debugging and run the app.
Press the INCREMENT Button to see the data change in PieChart

 

Leave a Reply

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