Android Read CSV File

Last modified on July 23rd, 2014 by Joe.

This Android tutorial is to explain how to read and use a CSV file in an Android application. There is nothing fancy and is a simple tutorial for beginners.

This tutorial will answer two questions,

  1. Where should I put the CSV file in Android?
  2. How to read that CSV file from the app?

Android-Csv-File-Read

Where to put the CSV file in Android

Create a folder named “raw” inside the “res” folder and put the CSV file in it. Here I am not discussing about loading a CSV file from an external memory card. May be I will write about it separately. This is to hold simple text data in a CSV file and use it inside the application. Instead of a database for holding data we can use this as a substitute when the data is simple and lesser.

How to read CSV file

Nothing special since its Android. All we are going to use our standard Java code. Its better to use our own code instead of going to an API. Following class is an utility to read CSV file and it can be used from within the Android application.

package com.javapapers.android.csvfileread.app;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class CSVFile {
    InputStream inputStream;

    public CSVFile(InputStream inputStream){
        this.inputStream = inputStream;
    }

    public List read(){
        List resultList = new ArrayList();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        try {
            String csvLine;
            while ((csvLine = reader.readLine()) != null) {
                String[] row = csvLine.split(",");
                resultList.add(row);
            }
        }
        catch (IOException ex) {
            throw new RuntimeException("Error in reading CSV file: "+ex);
        }
        finally {
            try {
                inputStream.close();
            }
            catch (IOException e) {
                throw new RuntimeException("Error while closing input stream: "+e);
            }
        }
        return resultList;
    }
}

So how to load the CSV file from “raw” folder and use the above utility to read it?

InputStream inputStream = getResources().openRawResource(R.raw.stats);
CSVFile csvFile = new CSVFile(inputStream);
List scoreList = csvFile.read();

Example Android Application with CSV File

Now lets look at this example Android application where we have used a CSV file to load data. We have used the Android custom list view layout to load and display the data from CSV file. We have seen how to use the custom list view layout in Android in the linked tutorial and go through it to understand the detail.

MainActivity.java

package com.javapapers.android.csvfileread.app;

import android.app.Activity;
import android.os.Parcelable;
import android.os.Bundle;
import android.widget.ListView;
import java.io.InputStream;
import java.util.List;


public class MainActivity extends Activity {
    private ListView listView;
    private ItemArrayAdapter itemArrayAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView) findViewById(R.id.listView);
        itemArrayAdapter = new ItemArrayAdapter(getApplicationContext(), R.layout.item_layout);

        Parcelable state = listView.onSaveInstanceState();
        listView.setAdapter(itemArrayAdapter);
        listView.onRestoreInstanceState(state);

        InputStream inputStream = getResources().openRawResource(R.raw.stats);
        CSVFile csvFile = new CSVFile(inputStream);
        List scoreList = csvFile.read();

        for(String[] scoreData:scoreList ) {
            itemArrayAdapter.add(scoreData);
        }
    }
}

ItemArrayAdapter.java

package com.javapapers.android.csvfileread.app;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;

public class ItemArrayAdapter extends ArrayAdapter {
	private List scoreList = new ArrayList();

    static class ItemViewHolder {
        TextView name;
        TextView score;
    }

    public ItemArrayAdapter(Context context, int textViewResourceId) {
        super(context, textViewResourceId);
    }

	@Override
	public void add(String[] object) {
		scoreList.add(object);
		super.add(object);
	}

    @Override
	public int getCount() {
		return this.scoreList.size();
	}

    @Override
	public String[] getItem(int index) {
		return this.scoreList.get(index);
	}

    @Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View row = convertView;
        ItemViewHolder viewHolder;
		if (row == null) {
			LayoutInflater inflater = (LayoutInflater) this.getContext().
                    getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			row = inflater.inflate(R.layout.item_layout, parent, false);
            viewHolder = new ItemViewHolder();
            viewHolder.name = (TextView) row.findViewById(R.id.name);
            viewHolder.score = (TextView) row.findViewById(R.id.score);
            row.setTag(viewHolder);
		} else {
            viewHolder = (ItemViewHolder)row.getTag();
        }
        String[] stat = getItem(position);
        viewHolder.name.setText(stat[0]);
        viewHolder.score.setText(stat[1]);
		return row;
	}
}

activity_mail.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.javapapers.android.csvfileread.app.MainActivity">
    <ListView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/listView"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="10dp" />
</RelativeLayout>

item_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/name"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_marginLeft="20dp" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/score"
        android:layout_alignParentTop="true"
        android:layout_alignParentRight="true"
        android:layout_marginRight="20dp" />
</RelativeLayout>

Download the Example Android Application

Android Read CSV File Application Source

Comments on "Android Read CSV File"

  1. Firoz Shaikh says:

    Useful Utility in Some Types of Application… Nice One Sir.

  2. Peter liu says:

    THANKS!
    IF the word is gibberish?
    How to solve?(utf-8)

  3. Anonymous says:

    List scoreList = csvFile.read();

    for(String[] scoreData:scoreList ) {
    itemArrayAdapter.add(scoreData);
    }
    over scoreData:scoreList it show me an error message .. “Type mismatch: cannot convert from element type Object to String[]”.. how to resolve it

  4. funlord says:

    The same problem:
    “Type mismatch: cannot convert from element type Object to String[]”.

  5. Akshat Rami says:

    use List instead of List , in whole example.

  6. Walt says:

    I had to use List when declaring scoreList instead of just List in order to access an element of a row after using scoreList.get(Index) to get a row.

    Great guide by the way. Very helpful

  7. Walt says:

    use List “” (Without quotes) instead of List and this works great

Comments are closed for "Android Read CSV File".