22

I have a CSV file in drawable/asset folder. In the CSV file there are four columns. First one is for date and rest three are for integer data.

I need to parse this CSV file and save the data in separate arrays.

I have searched for a solution, but I don't get proper idea on how to do this.

Ankita Shah
  • 1,866
  • 16
  • 31
Mohit Kanada
  • 15,274
  • 8
  • 31
  • 41
  • This may help you mate: http://stackoverflow.com/questions/5360628/get-and-parse-csv-file-in-android – necixy May 19 '11 at 11:11

1 Answers1

33

I like this csv reader: https://mvnrepository.com/artifact/net.sf.opencsv/opencsv/2.3

Just add it to your project.

Example code (assuming there is the file assets/test.csv):

        String next[] = {};
        List<String[]> list = new ArrayList<String[]>();

        try {
            CSVReader reader = new CSVReader(new InputStreamReader(getAssets().open("test.csv")));
            while(true) {
                next = reader.readNext();
                if(next != null) {
                    list.add(next);
                } else {
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

You can access the imported data with, for example,

list.get(1)[1]

That would return a string.

bendaf
  • 2,981
  • 5
  • 27
  • 62
nspo
  • 1,488
  • 16
  • 21
  • @PratikButani the `for(;;)` does that, so you can do it again after that loop it you want – chwi Jan 26 '14 at 15:03
  • CSVReader worked for me, after trying tons of other CSV parsing solutions. I am surprised good CSV parsing remains a difficult to implement solution. In my case I had to deal with multilines, and this is the only file which made it work. – zeeshan Nov 23 '15 at 02:50
  • What if I wanted to parse a CSV located on a Url? – Si8 Apr 09 '16 at 11:37
  • @Si8 Retrofit. ResponseBody. CSVReader reader = new CSVReader(response.body().charStream()); – Filowk May 01 '16 at 10:17