How to parse CSV file into an array in Android Studio
Solution 1
Where to put the CSV file in Android Create a folder named “raw” inside the “res” folder and put the CSV file in it.
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. In which array we will store items of csv file In these example it is scorelist arraylist .
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();
MainActivity.java
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
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>
For the whole source code you can refers to these link javapapers.com/wp-content/uploads/2014/07/CSVFileRead.zip
I think it will help
Solution 2
A better CSV parser handles quoted fields
import android.content.Context;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class CSVReader {
private class StringDArray {
private String[] data=new String[0];
private int used=0;
public void add(String str) {
if (used >= data.length){
int new_size= used+1;
String[] new_data=new String[new_size];
java.lang.System.arraycopy( data,0,new_data,0,used);
data=new_data;
}
data[used++] = str;
}
public int length(){
return used;
}
public String[] get_araay(){
return data;
}
}
private Context context;
public CSVReader(Context context){
this.context=context;
}
public List read(File file){
List resultList = new ArrayList();
try{
InputStream inputStream= new FileInputStream(file);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String csvLine;
final char Separator = ',';
final char Delimiter = '"';
final char LF = '\n';
final char CR = '\r';
boolean quote_open = false;
while ((csvLine = reader.readLine()) != null) {
//String[] row = csvLine.split(",");// simple way
StringDArray a=new StringDArray();
String token="";
csvLine+=Separator;
for(char c:csvLine.toCharArray()){
switch (c){
case LF: case CR:// not required as we are already read line
quote_open=false;
a.add(token);
token="";
break;
case Delimiter:
quote_open=!quote_open;
break;
case Separator:
if(quote_open==false){
a.add(token);
token="";
}else{
token+=c;
}
break;
default:
token+=c;
break;
}
}
if(a.length()>0 ) {
if(resultList.size()>0){
String[] header_row =(String[]) resultList.get(0);
if(a.length()>=header_row.length) {
String[] row = a.get_araay();
resultList.add(row);
}
}else{
String[] row = a.get_araay();
resultList.add(row);//header row
}
}
}
inputStream.close();
}catch (Exception e){
Toast.makeText(context,"Error : " + e.getMessage(), Toast.LENGTH_LONG).show();
}
return resultList;
}
}
Usage
File file=new File(path);
CSVReader csvReader=new CSVReader(activity.this);
List csv=csvReader.read(file);
if(csv.size()>0){
String[] header_row =(String[]) csv.get(0);
if(header_row.length>1){
String col1=header_row[0];
String col2=header_row[1];
}
}
Toast.makeText(activity.this,csv.size() + " rows", Toast.LENGTH_LONG).show();
Sample data used
ID,Name
1,Test Item 1
"2","Test Item 2"
"3","Test , Item 3"
4,Test Item 4
Solution 3
Disclaimer: I've never worked with Android, but I do know Java, so hopefully it's all the same.
That being said, you can try something like this.
Scanner scanner = new Scanner(new File("file.csv"));
ArrayList<String> pokemon = new ArrayList<>();
while(scanner.hasNextLine()) {
pokemon.add(scanner.nextLine().split(",")[1]);
}
scanner.close();
Varun Vu
Updated on July 05, 2022Comments
-
Varun Vu almost 2 years
i'm wondering how to parse a CSV file and just store the contents into an array. My csv file looks something like this:
1,bulbasaur,1,7,69,64,1,1 2,ivysaur,2,10,130,142,2,1
I only want the names, so the second field. I want to store all of these items in the csv into an array or arraylist of string.
Any ideas how to do this?
Any help would be greatly appreciated!
-
Dustin K almost 5 yearsWill this avoid splitting the string if a ',' is nested within nested quotes?
-
GeneCode about 4 yearswhere to put the public class CSVFile? in mainactivity.java?
-
Lidor Eliyahu Shelef over 3 yearsmy csv file is pretty large, and in the 'scoreData' there's only like 10-12 first lines of items from it. The csv file is without new lines or stuff, just ',' seperates between items