0

I am now trying to import csv files from a certain directory in sd card from an android device. Recently, I can successfully import a single csv files. However, I have no ideas on how to get the list of all csv files and then using a loop to import the csv file one by one.

This is the my code for importing single csv:

button_import_csv.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v){


            DatabaseHelper helper = new DatabaseHelper(getApplicationContext());
            SQLiteDatabase db = helper.getWritableDatabase();


            try{
                FileReader file = new FileReader("/sdcard/downloadedfolder/A1/adv_sales_order.csv");
                BufferedReader buffer = new BufferedReader(file);
                ContentValues contentValues=new ContentValues();
                String line = "";
                String tableName ="adv_sales_order";

                db.beginTransaction();
                while ((line = buffer.readLine()) != null) {
                    String[] str = line.split("\t");


                    contentValues.put("order_date", str[0]);
                    contentValues.put("cust_code", str[1]);
                    contentValues.put("customer_ref_no", str[2]);
                    contentValues.put("line_no", str[3]);
                    contentValues.put("item_code", str[4]);
                    contentValues.put("tran_code", str[5]);
                    contentValues.put("order_qty", str[6]);
                    db.insert(tableName, null, contentValues);

                }
                db.setTransactionSuccessful();
                db.endTransaction();
            }catch (IOException e){

            }
        }
    });

The columns for different csv fileS are not the same.(For example,some may has 4 columns named A,B,C,D and the other one may has columns named as C,D,E,F) Besides hard coding all columns for each csv file, are there any possible ways? Can anyone tell me any solution???Thank you.

1
  • I was posting my answer when you added your edit so I didn't spot it. So your problem is column names being different correct? Does the first line of the csv contain the column names?
    – Squonk
    May 8, 2014 at 7:14

1 Answer 1

0

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)...

A,B,C,D
valueA,valueB,valueC,valueD
...

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 names
line = buffer.readLine();
String[] cols = line.split("\t");
db.beginTransaction();
while ((line = buffer.readLine()) != null) {
    String[] str = line.split("\t");

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

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

7
  • Thank you, Squonk. But if the columns of different csv files are different, how can I process the file with a general code or a dynamic method??? May 8, 2014 at 7:12
  • @Helloheyyyy : I was posting my answer when you added your edit so I didn't spot it. Does the first line of the csv contain the column names?
    – Squonk
    May 8, 2014 at 7:18
  • No, there are no column names in the first line of the csv May 8, 2014 at 7:20
  • Are you in control of creating the csv files?
    – Squonk
    May 8, 2014 at 7:22
  • NO, the name of csv file cannot be changed. Is hard coding all insert commands with csv name the only way to achieve my objective??? May 8, 2014 at 7:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.