How to Parse the CSV File in Android Application

How to parse CSV file into an array in Android Studio

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

Get and Parse CSV file in android

Try something like this:

    //--- Suppose you have input stream `is` of your csv file then:

BufferedReader reader = new BufferedReader(new InputStreamReader(is));
try {
String line;
while ((line = reader.readLine()) != null) {
String[] RowData = line.split(",");
date = RowData[0];
value = RowData[1];
// do something with "data" and "value"
}
}
catch (IOException ex) {
// handle exception
}
finally {
try {
is.close();
}
catch (IOException e) {
// handle exception
}
}

Hope this helps.

Reading CSV File In Android App

Try OpenCSV - it will make your life easier.

First, add this package to your gradle dependencies as follows

implementation 'com.opencsv:opencsv:4.6'

Then you can either do

import com.opencsv.CSVReader;
import java.io.IOException;
import java.io.FileReader;

...

try {
CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
String[] nextLine;
while ((nextLine = reader.readNext()) != null) {
// nextLine[] is an array of values from the line
System.out.println(nextLine[0] + nextLine[1] + "etc...");
}
} catch (IOException e) {

}

or

CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
List myEntries = reader.readAll();

Edit after comment

try {
File csvfile = new File(Environment.getExternalStorageDirectory() + "/csvfile.csv");
CSVReader reader = new CSVReader(new FileReader(csvfile.getAbsolutePath()));
String[] nextLine;
while ((nextLine = reader.readNext()) != null) {
// nextLine[] is an array of values from the line
System.out.println(nextLine[0] + nextLine[1] + "etc...");
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "The specified file was not found", Toast.LENGTH_SHORT).show();
}

If you want to package the .csv file with the application and have it install on the internal storage when the app installs, create an assets folder in your project src/main folder (e.g., c:\myapp\app\src\main\assets\), and put the .csv file in there, then reference it like this in your activity:

String csvfileString = this.getApplicationInfo().dataDir + File.separatorChar + "csvfile.csv"
File csvfile = new File(csvfileString);

How can I read and show data from a csv file in Android?

You are indeed confused and mixing some things up. Let's go step by step.

STEP BY STEP, QUESTION BY QUESTION

  1. A class and an activity are not the same. You can read about it here and here. To put it in an easy way:

    • A class is a Java form.
    • For each screen in your app you will have a
      different activity. Each of them might have more than one class.
  2. Then, in Android, if you want to do any app (including the one which needs to read the .csv) you will need an activity, so that there is at least one screen in which the user can be. That is to say that the first thing you will need to do is to create an activity and add it to the manifest as the default activity (so that it appears together with the rest of apps). Do this (create activity), and then this (set it as default).

  3. Now you should be able to try the app in an emulator or a physical device and see an empty screen that does nothing.

  4. So far, so good. Now to the .csv reading problem. We will read the code as soon as the user enters the activity, when the activity is created (in the onCreate method). There should be a piece of code like the following one in your activity, otherwise, create it.

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}

  1. Now we will proceed to read the csv inside the onCreate (you could also do it when the user presses a button, etc.). Note that one thing is reading it and the other one is creating visible UI lists with it. Here you can see how to read a csv file (either if you have it in the sd or if you pack it with the app).

EDIT. Let's deep deeper into this step (5). As stated in the answer I have referenced, you need to:

Add this package to your gradle dependencies as follows

implementation 'com.opencsv:opencsv:4.6'

And then modify the onCreate (or wherever you want to read the csv):

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

try {
// OPTION 1: if the file is in the sd
File csvfile = new File(Environment.getExternalStorageDirectory() + "/csvfile.csv");
// END OF OPTION 1

// OPTION 2: pack the file with the app
/* "If you want to package the .csv file with the application and have it install on the internal storage when the app installs, create an assets folder in your project src/main folder (e.g., c:\myapp\app\src\main\assets\), and put the .csv file in there, then reference it like this in your activity:" (from the cited answer) */
String csvfileString = this.getApplicationInfo().dataDir + File.separatorChar + "csvfile.csv"
File csvfile = new File(csvfileString);
// END OF OPTION 2

CSVReader reader = new CSVReader(new FileReader("csvfile.getAbsolutePath()"));
String[] nextLine;
while ((nextLine = reader.readNext()) != null) {
// nextLine[] is an array of values from the line
System.out.println(nextLine[0] + nextLine[1] + "etc...");
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "The specified file was not found", Toast.LENGTH_SHORT).show();
}
}

FINALLY

Right, so this would be it. If you also wanted to represent this data in a list, a grid, etc., well, this is another question! However, just in case, you just need to use again the activity you created, but add the ListView to your layout and feed the list also in onCreate (for example). See a tutorial here.

Android- Select CSV file from Google Drive and parse it in java

I have parsed it using bufferReader and everything went perfect!

        Uri uri = data.getData();    
BufferedReader mBufferedReader = null;
String line;

try
{
InputStream inputStream = getContentResolver().openInputStream(uri);
mBufferedReader = new BufferedReader(new InputStreamReader(inputStream));
while ((line = mBufferedReader.readLine()) != null)
{
System.out.println("LLLLL: "+ line);
}
mBufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}

How to read csv file in android?

I have something like this;

public final List<String[]> readCsv(Context context) {
List<String[]> questionList = new ArrayList<String[]>();
AssetManager assetManager = context.getAssets();

try {
InputStream csvStream = assetManager.open(CSV_PATH);
InputStreamReader csvStreamReader = new InputStreamReader(csvStream);
CSVReader csvReader = new CSVReader(csvStreamReader);
String[] line;

// throw away the header
csvReader.readNext();

while ((line = csvReader.readNext()) != null) {
questionList.add(line);
}
} catch (IOException e) {
e.printStackTrace();
}
return questionList;
}

How to read a CSV file from a downloadable link in Android

I found this Kotlin code as one of the way to get the data in CSV by using Volley's stringRequest. In this case we get all the data as a string with rows being separated by \n and data in a row being separated by commas(,)

For this sample code, I'm accessing date from this URL: https://sample-videos.com/csv/Sample-Spreadsheet-10-rows.csv

val queue = Volley.newRequestQueue(this)
val url = "https://sample-videos.com/csv/Sample-Spreadsheet-10-rows.csv"
val stringRequest = StringRequest(
Request.Method.GET, url,
{ response ->
// Display the first 500 characters of the response string.
binding.csvDataTextView.text = "Response is: ${response.substring(0, 500)}"
val allLinesInResponse = response.substring(0)
var rowsData: List<String> = allLinesInResponse.split("\n")
Log.d("abc", "The Volley request worked")
},
{
Log.d("abc", "The Volley request didn't work!")
})
queue.add(stringRequest)
queue.start()

There may be other better ways, but this is one of those which work.



Related Topics



Leave a reply



Submit