Open In App

How to Plot a Graph in Android Using CSV File?

Last Updated : 28 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

csvscreenshot

gfg.csv

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.

rawGFG

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.

github

XML




<RelativeLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    tools:context=".MainActivity">
 
    <com.github.mikephil.charting.charts.LineChart
        android:id="@+id/lineChart"
        android:layout_width="match_parent"
        android:layout_height="615dp" />
 
</RelativeLayout>


Step 5: Working With Java File

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

Java




package com.example.gfgapp;
 
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.Toast;
 
import androidx.appcompat.app.AppCompatActivity;
 
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.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
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.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
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;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
      
        lineChart = findViewById(R.id.lineChart);
 
        // 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");
        lineDataSet.setColors(ColorTemplate.MATERIAL_COLORS);
 
      
        lineDataSet.setValueTextColor(Color.BLACK);
        lineDataSet.setValueTextSize(16f);
 
        // Creating a LineData object with the LineDataSet
        LineData lineData = new LineData(lineDataSet);
 
        // Seting up the LineData object to the LineChart
        lineChart.setData(lineData);
 
        // Seting a description for the LineChart
        Description description = new Description();
        description.setText("Line Chart");
        lineChart.setDescription(description);
 
        // Configuring the X-axis
        XAxis xAxis = lineChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setGranularity(1f);
 
    
        YAxis leftAxis = lineChart.getAxisLeft();
        leftAxis.setGranularity(1f);
 
        // Disabling the right Y-axis
        lineChart.getAxisRight().setEnabled(false);
 
        // Initializing lists to store years and product names
        years = new ArrayList<>();
        products = new ArrayList<>();
 
        readDataFromCSV();
 
        setupChart();
 
        // Seting up OnChartValueSelectedListener to handle selection events
          // When Someone Clicks On The Line Chart It Will Show The Product Name
        lineChart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
            @Override
            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();
                }
            }
 
            @Override
            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;
                    continue;
                }
                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) {
            e.printStackTrace();
        }
    }
 
  
    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
        years.add(year);
        products.add(product);
    }
 
   
    private void setupChart() {
        lineDataSet.notifyDataSetChanged();
        lineChart.getData().notifyDataChanged();
        lineChart.notifyDataSetChanged();
 
        // Displaying maximum 6 visible entries on the x-axis
        lineChart.setVisibleXRangeMaximum(6);
        // 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));
    }
 
    @Override
    protected void onDestroy() {
        super.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;
        }
 
        @Override
        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.

Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads