Android GraphView – How to Plot Graph from CSV File in Android using GraphView

This android tip will focus on how to create graph in android using GraphView library. The data for the graph will be fetch from a CSV file.

In other to learn how you can fetch data from local or remote csv file, I will refer you to my tutorial on How to read CSV file from Remote Server or Assets Folder in Android.

This tutorial is based on the above listed tutorial and it is important you read it first.

But if you have your data source ready which does not come from csv file, you can still use this process but you will slightly modify your code to work base on your use case.

Android Graph Libraries

There are so many android graph libraries out there you can use to plot both simple and complex graphs. Some are very complex while others need lots of configuration or code for a simple line graph.

In this android tips, we will use android GraphView library. Android GraphView helps you to draw a graph in android with ease.

To learn how to use GraphView to plot a graph in android, we will first add the library as one of the gradle library dependencies.

compile 'com.jjoe64:graphview:4.2.1'
compile 'com.jjoe64:graphview:4.2.1'

Android GraphView supports different kinds of graphs like LineGraph, Barchart, PointGraph. You can also plot a real-time graph using GraphView.)

On GraphView main website, this is how this android library is described – “GraphView – open source graph plotting library for Android. GraphView is a library for Android to programmatically create flexible and nice-looking diagrams. It is easy to understand, to integrate and to customize. Create Line Graphs, Bar Graphs, Point Graphs or implement your own custom types.”

See the screen-shot of what we are planning to do below.

android graphview

1. Create a new android app

Go to File menu

Click on New menu

Click on Android Application

Enter Project name: AndroidGraphView

Package: com.inducesmile.androidgraphview

Select Empty Activity

Name your activity: MainActivity

Keep other default selections

Continue to click on next button until Finish button is active, then click on Finish Button.

2. Add the code below to activity_main.xml layout file

Open the default activity_main.xml file Android Studio created for us. Add a Button and GraphView widgets on the layout file.

When the button is clicked it will read the content of the .cvs file and it will plot a graph based on the data read from the cvs file on the GraphView.

Add the code below to the layout file.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.inducesmile.androidreadcvsfile.MainActivity">
    
    <Button
        android:id="@+id/load_file_from_server"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/read_cvs_file_from_remote_server"
        android:background="@color/colorAccent"/>

    <com.jjoe64.graphview.GraphView
        android:layout_width="match_parent"
        android:layout_height="300dip"
        android:layout_marginTop="24dp"
        android:id="@+id/graph" />

</LinearLayout>

3. Update AndroidManifest.xml

Since the application is going to make a network call, we will add user permission for Internet. Open your project AndroidManifest.xml file and add the code below.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.inducesmile.androidremotetextfile">
    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

4. Update MainActivity.java

It is important to understand that reading a file from a remote server or location over the internet has slight different approach with reading from from with the application.

For remote reading of .cvs file or any kind of file, it has to be done in a background thread since android gets angry if you implement network calls in the main UI thread.

For the remote reading of the .cvs in android, we will use the old AsyncTask class.

We have created two methods (createLineGraph() and createBarChartGraph())that are responsible for creating a LineGraph and a Barchart. You can call any of the methods depending on the type of graph you want to plot.

Open the MainActivity.java file and add the code below.

import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.ValueDependentColor;
import com.jjoe64.graphview.series.BarGraphSeries;
import com.jjoe64.graphview.series.DataPoint;
import com.jjoe64.graphview.series.LineGraphSeries;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
    private static final String TAG = MainActivity.class.getSimpleName();
    private GraphView mGraph;
    private static final String PATH_TO_SERVER = "path to remote .csv file";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mGraph = (GraphView) findViewById(R.id.graph);
        Button loadTextButton = (Button)findViewById(R.id.load_file_from_server);
        loadTextButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DownloadFilesTask downloadFilesTask = new DownloadFilesTask();
                downloadFilesTask.execute();
            }
        });
    }
    private List<String[]> readCVSFromAssetFolder(){
        List<String[]> csvLine = new ArrayList<>();
        String[] content = null;
        try {
            InputStream inputStream = getAssets().open("local.cvs");
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
            String line = "";
            while((line = br.readLine()) != null){
                content = line.split(",");
                csvLine.add(content);
            }
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return csvLine;
    }
    private class DownloadFilesTask extends AsyncTask<URL, Void, List<String[]>> {
        protected List<String[]> doInBackground(URL... urls) {
            return downloadRemoteTextFileContent();
        }
        protected void onPostExecute(List<String[]> result) {
            if(result != null){
                createLineGraph(result);
            }
        }
    }
    private void createLineGraph(List<String[]> result){
        DataPoint[] dataPoints = new DataPoint[result.size()];
        for (int i = 0; i < result.size(); i++){
            String [] rows = result.get(i);
            Log.d(TAG, "Output " + Integer.parseInt(rows[0]) + " " + Integer.parseInt(rows[1]));
            dataPoints[i] = new DataPoint(Integer.parseInt(rows[0]), Integer.parseInt(rows[1]));
        }
        LineGraphSeries<DataPoint> series = new LineGraphSeries<DataPoint>(dataPoints);
        mGraph.addSeries(series);
    }
    private void createBarChartGraph(List<String[]> result){
        DataPoint[] dataPoints = new DataPoint[result.size()];
        for (int i = 0; i < result.size(); i++){
            String [] rows = result.get(i);
            Log.d(TAG, "Output " + Integer.parseInt(rows[0]) + " " + Integer.parseInt(rows[1]));
            dataPoints[i] = new DataPoint(Integer.parseInt(rows[0]), Integer.parseInt(rows[1]));
        }
        BarGraphSeries<DataPoint> series = new BarGraphSeries<DataPoint>(dataPoints);
        mGraph.addSeries(series);
        series.setValueDependentColor(new ValueDependentColor<DataPoint>() {
            @Override
            public int get(DataPoint data) {
                return Color.rgb((int) data.getX()*255/4, (int) Math.abs(data.getY()*255/6), 100);
            }
        });
        series.setSpacing(50);
    }
    private List<String[]> downloadRemoteTextFileContent(){
        URL mUrl = null;
        List<String[]> csvLine = new ArrayList<>();
        String[] content = null;
        try {
            mUrl = new URL(PATH_TO_SERVER);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        try {
            assert mUrl != null;
            URLConnection connection = mUrl.openConnection();
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line = "";
            while((line = br.readLine()) != null){
                content = line.split(",");
                csvLine.add(content);
            }
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return csvLine;
    }
}

You can see how simple it is to use GraphView in your android application. You can star GraphView library in Github if you feel that it is helpful and has saved you many hours you would have put to develop it yourself.

Have you used any other android graph library that is really good and simple to implement.? If so we will like to hear from you or share your experience using it with us.

OTHER INTERESTING POSTS:

Add a Comment