Android CSV Parser

In the previous serious of tutorial we have see how to Parse JSON in android  , and here in this post we shall see how to parse csv file in android and to do that i am placing csv file inside the asset folder of the project directory and parse to show data on listview.


XML Layout


Create xml layout list_items.xml this xml layout represents how the rows of listview looks like.

file : list_items.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:padding="15dp" >

    <TextView
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:textColor="#92130E"
        android:textSize="18dp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/color"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:textColor="#1B920E"
        android:textSize="18dp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/price"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#0E2092"
        android:textSize="18dp"
        android:textStyle="bold" />

</LinearLayout>


CSV Parser Class


CSV stands for comma separated value file , which is basically a plain text file in which values are separated by "," .

file : product.csv
name,color,price
iphone,gold,$1144.00
Samsung Glaxay S5,Shimmery White,$1011.00
Moto G,Black,$248.04
Nokia XL,Bright Green,$255.31
HTC One,Silver,$953.33  

Here In this tutorial i am parsing CSV File which is keep inside the asset folder of the project directory .



Create a class CSVReader and inside this call i am defining a method called ReadCSV() the purpose of this method is to parse csv and return it in the form of ArrayList of Hashmap.

file : CSVReader.java
package com.pavan.csvparserdemo;

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

import android.content.Context;

public class CSVReader {

    Context context;

    String file_name;

    ArrayList<HashMap<String, String>> CSVData;

    public CSVReader(Context context, String file_name) {
        this.context = context;

        this.file_name = file_name;

    }

    public ArrayList<HashMap<String, String>> ReadCSV() throws IOException {

        InputStream is = context.getAssets().open(file_name);

        InputStreamReader isr = new InputStreamReader(is);

        BufferedReader br = new BufferedReader(isr);

        String line;

        String cvsSplitBy = ",";

        br.readLine();

        CSVData = new ArrayList<HashMap<String, String>>();

        while ((line = br.readLine()) != null) {

            String[] row = line.split(cvsSplitBy);

            HashMap<String, String> hm = new HashMap<String, String>();

            for (int i = 0; i < row.length; i++) {

                hm.put("row[" + i + "]", row[i]);

            }
            CSVData.add(hm);
        }
        return CSVData;

    }

}

Main ListActivity


Create a class MainActivity which extends ListActivity , create a inner class Mytask which extends AsyncTask ,Inside the doInBackground() method call for ReadCSV() method on CSVReader object which returns  ArrayList of hashmap finally bind this data to listview using SimpleListAdapter inside onPostExecute method .

file : MainActivity.java
package com.pavan.csvparserdemo;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.ListActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;

public class MainActivity extends ListActivity {

    ArrayList<HashMap<String, String>> csvdata;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        new Mytask().execute();

    }

    class Mytask extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {
            CSVReader csvreader = new CSVReader(MainActivity.this,
                    "product.csv");

            try {
                csvdata = csvreader.ReadCSV();

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);

            // keys of hashmap
            String[] from = { "row[0]", "row[1]", "row[2]" };

            // view id's to which data to be binded
            int[] to = { R.id.name, R.id.color, R.id.price };

            // Creating Adapter
            ListAdapter adapter = new SimpleAdapter(MainActivity.this, csvdata,
                    R.layout.list_items, from, to);

            // Setting Adapter to ListView
            setListAdapter(adapter);

        }

    }

}



3 comments:

Esa said...

very nice.. how can i write some data into csv file

PADMANAV said...

Thank You. How can i do same thing using Excel file.

Konstantin Levchenko said...

Большое спасибо за Ваши уроки! Странно что человек не написавший ни единого слова на русском языке может объяснить урок лучше чем русско говорящие учителя. Еще раз большое спасибо.

Post a Comment