w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Import multiple .csv file into android sqlite database

There are two possibilities I can think of...

First: If you are in control of the filenames then give them names with a sequential numeric aspect, e.g., file1.csv, file2.csv etc You can then simply use a for loop to build the filenames and process them. Example...

// Lets say you have 5 files named file1.csv thru file5.csv
for(int i = 1; i < 6; i++) {
    String filename = "file" + i + ".csv";
    // Process the file which has the above filename

Second: Get all of the files in the directory using the listFiles() method. Example...

// This code assumes you have a File object for the directory
called dir
File[] files = dir.listFiles();
for(int i = 0; i < files.length; i++) {
    String filename = files[i].getAbsolutePath();
    if (filename.endsWith(".csv")) {
        // Process the file which has the above filename

I'm not sure if either of the code blocks above are perfect but basically they both simply use a for loop. There are other ways but those are the most straight-forward.

EDIT: Some csv files use the first line to describe the column names. In some ways this is a bit like a schema of a dataset. Example (using comma-separated values)...


Using this approach means you can get access to the column names by reading the first line and splitting it to make an array. You can then use a for loop to put the ContentValues. Try the following...

// Read the first line separately and split to get the column
line = buffer.readLine();
String[] cols = line.split("	");
while ((line = buffer.readLine()) != null) {
    String[] str = line.split("	");

    for (int i = 0; i < cols.length; i++) {
        contentValues.put(cols[i], str[i]);
    db.insert(tableName, null, contentValues);

BTW I notice you're splitting on " " so make sure your column names on the first line are tab-delimited (obviously).

© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.