-2

I have problem when trying to read the csv file, the error appears like this : java.lang.ArrayIndexOutOfBoundsException: length=1; index=1 . I have tried searching in StackOverflow, the error appears same as above.

Code :

private void readCSVFile(String csvNameFile) {
    try {
        File readFolderCSV = new File(Environment.getExternalStorageDirectory() + "/Download/" + csvNameFile);
        CSVReader csvReader = new CSVReader(new FileReader(readFolderCSV.getAbsoluteFile()));
        String[] nextLine;
        while((nextLine = csvReader.readNext()) != null) {
            Log.e("TAG", nextLine[0] + nextLine[1] + nextLine[2] + nextLine[3] + nextLine[4]);
        }
    } catch (Exception e) {
        e.printStackTrace();
        Toast.makeText(MasterUoM.this, "The specified file was not found", Toast.LENGTH_SHORT).show();
    }
}

MyCSVFile :

1

  • 1
    That means you only have one item in that array (at index 0) but you are trying to access a second one (index 1). So, most likely, `nextLine[1]` causes the `Exception` because there is only one `String` in it (the entire line, maybe?). – deHaar Jan 09 '20 at 06:57
  • 1
    Based on your screenshot, it seems there are only going to be only 2 objects in your nextLine[] array. So the nextLine[2] or above should give an ArrayIndexOutOfBoundException as expected. – Shivam Puri Jan 09 '20 at 06:57
  • Your `csv` contains only 2 columns in each row, but you try to get 3, 4, 5 which cause the exception – Md. Asaduzzaman Jan 09 '20 at 06:58
  • @Md.Asaduzzaman MyCSVFile just an example. How about when i have much data of Categories Name in Category Name column? – Muhammad Rafi Bahrur Rizki Jan 09 '20 at 07:03

2 Answers2

2

Your problem is here:

while((nextLine = csvReader.readNext()) != null) {
            Log.e("TAG", nextLine[0] + nextLine[1] + nextLine[2] + nextLine[3] + nextLine[4]);
        }

Your are logging without length safety. You have a line where nextLine[1] does not exist. That's because csvreader does not return cells but lines.

You need to split the line using the split method. Java split string to array and again check if the length of the table is enough.

3,4 and 5 cell access will cause you the same trouble.

Athanasios Kataras
  • 25,191
  • 4
  • 32
  • 61
1

It seems you are trying to fetch column[2] and column[3] & column[4] but csv is not having 5 columns,

 Log.e("TAG", nextLine[0] + nextLine[1] + nextLine[2] + nextLine[3] + nextLine[4]);

You can check it by printing nextLine.length().

Vivek
  • 376
  • 1
  • 14