Android CSV file


In this Android tip, I am going to show you how to read data from a CSV file to display in a ListView. A CSV is a known as a comma separated values file. You can use it to store data in a table structured format. To create a CSV file in Ms. Excel, you input the data in a sheet. Then save the file with CSV extension. In the example application below, i have a CSV file called foodlist.csv saved in the res/raw folder of the project. It has two columns: ID, and Name as shown in the picture below.

Android csv file


To read the CSV file in the res/raw folder, you need to use the openRawResource() method of the Resources instance. You have to pass to this method a resource id which points to the foodlist.csv file (R.raw.foodlist). The openRawResource() method returns an InputStream object. Then you use BufferedReader class to read rows or lines from the file. When you create a BufferedReader object, you have to pass an object of InputStreamReader class that wraps the InputStream object to BufferedReader 's constructor.

Now to have an example application on reading data from CSV file to populate a ListView, you create a new Android project with the name CSVListView. The CSV file to be read is placed in the res/raw folder. In my case, I have foodlist.csv. In the activity_main.xml file, you add a ListView as shown below.



<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.example.csvlistview.MainActivity" >

   <ListView
     android:id="@+id/listview"
     android:layout_width="match_parent"
     android:layout_height= "wrap_content"
   />

</RelativeLayout>

In the res/layout file, you create an xml file called listrow.xml that is the row template of the ListView.

<?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" >
  
   <TextView
   android:id="@+id/txtid"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:padding="10sp"
   android:textStyle="bold" >
</TextView>
<TextView
   android:id="@+id/txtname"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:padding="10sp"
   android:textStyle="bold" >
</TextView>

</LinearLayout>

Next, in the src folder, you create a class called MyListAdapter that extends the ArrayAdapter class. An instance of the MyListAdapter class is used to bind data read from the foodlist.csv file to the ListView.

package com.example.csvlistview;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class MyListAdapter extends ArrayAdapter<String[]>{
int groupid;
List<String[]> items;
Context context;
String path;

public MyListAdapter(Context context, int vg, int id, List<String[]> items){
super(context,vg, id, items);
this.context=context;
groupid=vg;
this.items=items;

}
static class ViewHolder {
   public TextView textid;
   public TextView textname;
  
}

public View getView(int position, View convertView, ViewGroup parent) {

View rowView = convertView;
if(rowView==null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView= inflater.inflate(groupid, parent, false);
ViewHolder viewHolder = new ViewHolder();
viewHolder.textid = (TextView) rowView.findViewById(R.id.txtid);
viewHolder.textname = (TextView) rowView.findViewById(R.id.txtname);
rowView.setTag(viewHolder);
}
     // Fill data
     ViewHolder holder = (ViewHolder) rowView.getTag();
     String[] row=items.get(position);    
     holder.textid.setText(row[0]);
     holder.textname.setText(row[1]);
    
     return rowView;
}

}

In the MainActivity class that hosts the ListView, you write code to read data from the foodlist.csv file, create an instance of MyListAdapter class, and set the instance to the ListView to display the data.

package com.example.csvlistview;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;

public class MainActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
InputStream inputStream = getResources().openRawResource(R.raw.foodlist);
CSVFile csvFile = new CSVFile(inputStream);
List<String[]> foodList = csvFile.read();
MyListAdapter adapter=new MyListAdapter(this, R.layout.listrow,R.id.txtid, foodList);
ListView listView=(ListView)findViewById(R.id.listview);
listView.setAdapter(adapter);
}

private class CSVFile {
   InputStream inputStream;

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

   public List<String[]> read(){
   //
     List<String[]> resultList = new ArrayList<String[]>();
     BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
     try {
        String line;
        while ((line = reader.readLine()) != null) {
           String[] row = line.split(",");
           resultList.add(row);
        }
     }
     catch (IOException e) {
        Log.e("Main",e.getMessage());
     }
     finally {
        try {
           inputStream.close();
        }
        catch (IOException e) {
         Log.e("Main",e.getMessage());
        }
     }
     return resultList;
   }
}


}


Android-CSV-file

Posted by: Dara | post date: 11-26-2014 | Subject: Android Apps Development

write programming tip



This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.