How to read from CSV file in Android Android 06.07.2017

android_csv.png

CSV is a known as a comma separated values file. You can use it to store data in a table structured format.

For example, save following table to app/src/main/assets/movies.csv file of the project. It has two columns: title, and year as shown below.

The Shawshank Redemption,1994
The Godfather,1972
The Dark Knight,2008
The Godfather: Part II,1974

We are going to our standard Java code. Following class is an utility to read CSV file and it can be used from within the Android application.

public class CSVReader {
    Context context;
    String fileName;
    List<String[]> rows = new ArrayList<>();

    public CSVReader(Context context, String fileName) {
        this.context = context;
        this.fileName = fileName;
    }

    public List<String[]> readCSV() throws IOException {
        InputStream is = context.getAssets().open(fileName);
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String line;
        String csvSplitBy = ",";

        br.readLine();

        while ((line = br.readLine()) != null) {
            String[] row = line.split(csvSplitBy);
            rows.add(row);
        }
        return rows;
    }
}

Following is example of usage.

public class MainActivity extends AppCompatActivity {
    RatingBar ratingBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        List<String[]> rows = new ArrayList<>();
        CSVReader csvReader = new CSVReader(RatingActivity.this, "movies.csv");
        try {
            rows = csvReader.readCSV();
        } catch (IOException e) {
            e.printStackTrace();
        }

        for (int i = 0; i < rows.size(); i++) {
            Log.d(Constants.TAG, String.format("row %s: %s, %s", i, rows.get(i)[0], rows.get(i)[1]));
        }
    }
}