I am trying to read a CSV file and have it display the contents as a basic list for an Android app. I am using the method given by Kopfgeldjaeger in this thread.
I have added a couple of ‘toasts’ which either display ‘success’ or ‘fail’ at the bottom of the Android screen if the code managed (or didn’t manage) to load the CSV file properly. See below:
try {
CSVReader reader = new CSVReader(new InputStreamReader(getAssets().open("file.csv")));
for(;;) {
next = reader.readNext();
if(next != null) {
list.add(next);
} else {
break;
}
}
Toast.makeText(getApplicationContext(), "SUCCESS",
Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "FAIL",
Toast.LENGTH_SHORT).show();
}
When I load the app, I get the ‘SUCCESS’ message, so all is well so far. Now, I’d like to see if I can load any of the data. In Kopfgeldjaeger’s answer, it is suggested that I could access a string using the following code:
list.get(1)[1]
So, in order to check that it’s worked, I try to generate another toast, as follows:
Toast.makeText(getApplicationContext(), list.get(1)[1],
Toast.LENGTH_SHORT).show();
This added toast causes the program to fail to load properly. The question is, have I gotten the toast syntax wrong, or is my CSV file not loading properly?
There are a couple of things to check:
list.size()andlist.get(0).lengthto see if they’re both at least 2.As a recommendation: the referenced csv reader is part of ByteCode’s OpenCSV. You may want to include the latest source code or jar from that project. It supports custom delimiter characters and also provides a shorthand for parsing all the csv data into a list of string arrays: