Open In App

How to Plot a Graph in Android Using CSV File?

Last Updated : 28 Aug, 2023
Like Article

When we are dealing with large amounts of data sets and if we want to display the data graphically then it becomes sometimes tough to generate a graph using that data so in this article we are going to implement this in an easy manner and you can add any types of graph and charts like BarChart, PieChart and many more. CSV File that we are going to use in this article:



A sample video is given below to get an idea about what we are going to do in this article and when we click on the graph it’ll show the product name in Toast format.

Step-by-Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.

Step 2: Adding Dependencies

We Have To Add Two Dependencies in build.gradle file one dependency will be used for opening the csv file and one will be used for plotting the Graph add these two Dependencies and sync your project.

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

Step 3: Create Your CSV File and Paste It

Create Your CSV File and Paste that csv file into the res > raw folder if you don’t have one you can create a raw folder by right-clicking on the raw folder and selecting New Resource Directory into and name it as Directory Name as Raw and Resource type as Raw.


Step 4: Working With Activity File

After That In Your XML File Create a view For the graph That will be displayed from csv file, You Can also create charts to do that just write com. Then lots of options will be visible that you can use and for the same graph.



        android:layout_height="615dp" />

Step 5: Working With Java File

Go to the file and refer to the following code. Below is the code for the file. Comments are added inside the code to understand the code in more detail.


package com.example.gfgapp;
import android.content.res.Resources;
import android.os.Bundle;
import android.widget.Toast;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.opencsv.CSVReader;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
    private LineChart lineChart;
    private LineDataSet lineDataSet;
    private ArrayList<Entry> data;
    private List<String> years;
    private List<String> products;
    protected void onCreate(Bundle savedInstanceState) {
        lineChart = findViewById(;
        // Initializing the data list for chart entries
        data = new ArrayList<>();
        // Creating a LineDataSet with the data and a label for the legend
        lineDataSet = new LineDataSet(data, "Sales Info");
        // Creating a LineData object with the LineDataSet
        LineData lineData = new LineData(lineDataSet);
        // Seting up the LineData object to the LineChart
        // Seting a description for the LineChart
        Description description = new Description();
        description.setText("Line Chart");
        // Configuring the X-axis
        XAxis xAxis = lineChart.getXAxis();
        YAxis leftAxis = lineChart.getAxisLeft();
        // Disabling the right Y-axis
        // Initializing lists to store years and product names
        years = new ArrayList<>();
        products = new ArrayList<>();
        // Seting up OnChartValueSelectedListener to handle selection events
          // When Someone Clicks On The Line Chart It Will Show The Product Name
        lineChart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
            public void onValueSelected(Entry e, Highlight h) {
                // Get the index of the selected entry
                int index = (int) e.getX();
                if (index >= 0 && index < products.size()) {
                      // Geting corresponding product name from the products list
                    String productName = products.get(index);
                      // Displaying toast message with the selected product name
                    Toast.makeText(MainActivity.this, productName, Toast.LENGTH_SHORT).show();
            public void onNothingSelected() {
                // Let it be empty only
    private void readDataFromCSV() {
        Resources res = getResources();
          // Make Sure You Specify Your CSV File Name in My Case the CSV File Name is gfg
        InputStream inputStream = res.openRawResource(R.raw.gfg);
        try {
            CSVReader reader = new CSVReader(new InputStreamReader(inputStream));
            String[] nextLine;
            // Flag to skip the first line of the CSV file that is header
            boolean isFirstLine = true;
            while ((nextLine = reader.readNext()) != null) {
                if (isFirstLine) {
                    // Skiping the first line header of the CSV file
                    isFirstLine = false;
                if (nextLine.length >= 3) {
                    // Extracting the year from the CSV data
                    String year = nextLine[0].trim();
                    // Extract and parsing the sales value parsing because the sales value
                    // is written with comma like that (12,500)
                    float sales = Float.parseFloat(nextLine[1].replace(",", "").trim());
                    String product = nextLine[2].trim();
                    addEntryToChart(sales, year, product);
        } catch (IOException e) {
    private void addEntryToChart(float sales, String year, String product) {
        data.add(new Entry(data.size(), sales));
        // Storing year and product names for each data entry
    private void setupChart() {
        // Displaying maximum 6 visible entries on the x-axis
        // Moving the chart view to the last 7 entries
        lineChart.moveViewToX(data.size() - 7);
        // Seting the description text for the graph that is visible at the right side bottom
        lineChart.getDescription().setText("Sales Info");
        lineChart.getXAxis().setValueFormatter(new YearValueFormatter(years));
    protected void onDestroy() {
    // Custom ValueFormatter class for X-axis labels
    public static class YearValueFormatter extends ValueFormatter {
        private final List<String> years;
        public YearValueFormatter(List<String> years) {
            this.years = years;
        public String getFormattedValue(float value) {
            // Type Casting float value to integer index
            int index = (int) value;
            if (index >= 0 && index < years.size()) {
                // Retrieving the year string from
                  // the years list based on the index
                return years.get(index);
            // Returning empty string if
              // the index is out of bounds
            return "";

Make Sure if you’re using other graphs/charts create the object for that only in the Java file we have used a line graph so we have used lineDataSet to specify the values.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads