How to draw PieChart using MPAndroidChart in Android

In this android programming source code example, we are going to draw PieChart using MPAndroidChart in Android.

You can copy and adopt this source code example to your android project without reinventing the wheel.

Below is a step by step source code to draw PieChart using MPAndroidChart in Android.

activity_main.xml

<?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=".AndroidChart.AndroidChartActivity2">

    <com.github.mikephil.charting.charts.PieChart
        android:id="@+id/pieChart"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.data.Entry;
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 AndroidChartActivity2 extends AppCompatActivity {
    private PieChart pieChart;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_android_chart2);
        pieChart = (PieChart)findViewById(R.id.pieChart);
        PieDataSet pieDataSet = new PieDataSet(getData(),"Inducesmile");
        pieDataSet.setColors(ColorTemplate.COLORFUL_COLORS);
        PieData pieData = new PieData(pieDataSet);
        pieChart.setData(pieData);
        pieChart.animateXY(5000, 5000);
        pieChart.invalidate();
    }

    private ArrayList getData(){
        ArrayList<PieEntry> entries = new ArrayList<>();
        entries.add(new PieEntry(945f, "Ayo"));
        entries.add(new PieEntry(1030f, "Adekola"));
        entries.add(new PieEntry(1143f, "Henry"));
        entries.add(new PieEntry(1250f, "Mark"));
        return entries;
    }
}

app/build.gradle

implementation 'com.github.Philjay:MPAndroidChart:v3.1.0'

If you have any question or suggestions kindly use the comment box or you can contact us directly through our contact page below.

Add a Comment