0

I am trying to parse a simple csv file in android using the openCSV library. The problem I am runnning into is that it is reading only the first column and nothing else. Can someone look into the code and advice what could be going wrong?

public final List<List<String>> readCsv(Context context) {
    List<String> exerciseList = new ArrayList<String>();
    List<String> setsList = new ArrayList<String>();
    List<String> repsList = new ArrayList<String>();
    List<List<String>> combinedList = new ArrayList<List<String>>();
    AssetManager assetManager = context.getAssets();

    try {
        InputStream csvStream = assetManager.open("dummyexerciseplan.csv");
        InputStreamReader csvStreamReader = new InputStreamReader(csvStream);
        CSVReader csvReader = new CSVReader(new InputStreamReader(getAssets().open("dummyexerciseplan.csv")),',');
        String[] line;

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

        while ((line = csvReader.readNext()) != null) {
            System.out.println(line.toString());
            exerciseList.add(line[0]);
            setsList.add(line[1]);
            repsList.add(line[2]);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    combinedList.add(exerciseList);
    combinedList.add(setsList);
    combinedList.add(repsList);

    return combinedList;
}

This gives an array out of bounds exception since there is the length of the array is only 1 and i am indexing into the second and the third elements as well.

This is what the csv file looks like:

Exercise Name,Sets,Repetitions,Day Of Week 
Bent over two-dumbell row,2,12,1 
Pull-Ups,2,12,1
TheBlueNotebook
  • 1,204
  • 3
  • 15
  • 35
  • Is that your csv file exactly? It doesn't happen to have new-lines or anything like that? – Ben van Gompel Oct 22 '15 at 04:04
  • No I am sorry. It does have new lines. I will edit my question. – TheBlueNotebook Oct 22 '15 at 05:24
  • I'm sure it has nothing to do with your issue, but there seem to be a few unused variables in your code: `assetManager`, `csvStream`, `csvStreamReader` – Ben van Gompel Oct 22 '15 at 06:01
  • Having said that, getting rid of these variables, embedding the resulting code in my Android app, makes it run just fine. – Ben van Gompel Oct 22 '15 at 06:19
  • Wow. That's really puzzling. I got rid of the unused variables (sorry about that. Was trying something. Forgot to remove the lines). and I still have the same runtime exception. – TheBlueNotebook Oct 22 '15 at 13:14
  • Okay. I figured out the problem. I had a trailing space in the end. That one line was getting read as a single membered array in itself and that was what was causing the out of bounds exception. – TheBlueNotebook Oct 22 '15 at 14:02

1 Answers1

0

The problem was with the csv file I was using. It had a trailing whitespace in the last line. This was the single member array which was causing the out of bounds exception.

TheBlueNotebook
  • 1,204
  • 3
  • 15
  • 35