0

In my Android app, I am converting the SQLite .db file to a .csv file and saving on an external storage - this part has gone fine.

However, despite all the data being present, which is 23 columns,and when I put through a sample set of data, the output looked like:

"column_1_heading","column_2_heading","column_1_data","column_2_data",

where everything is in a single row and surrounded by quotation marks.

What I am after is for it to be in separate rows, without the quotation marks, such as:

column_1_heading,column_2_heading
column_1_data,column_2_data

They do not need to be lined up as columns, just in order in separate rows.

The code that I am using to perform the conversion is strongly based on this answer, the code of which is reproduced below:

        File dbFile=getDatabasePath("MyDBName.db");
        DBHelper dbhelper = new DBHelper(getApplicationContext());
        File exportDir = new File(Environment.getExternalStorageDirectory(), "");
        if (!exportDir.exists())
        {
            exportDir.mkdirs();
        }

        File file = new File(exportDir, "csvname.csv");
        try
        {
            file.createNewFile();
            CSVWriter csvWrite = new CSVWriter(new FileWriter(file));
            SQLiteDatabase db = dbhelper.getReadableDatabase();
            Cursor curCSV = db.rawQuery("SELECT * FROM contacts",null);
            csvWrite.writeNext(curCSV.getColumnNames());
            while(curCSV.moveToNext())
            {
                //Which column you want to exprort
                String arrStr[] ={curCSV.getString(0),curCSV.getString(1), curCSV.getString(2)};
                csvWrite.writeNext(arrStr);
            }
            csvWrite.close();
            curCSV.close();
        }
        catch(Exception sqlEx)
        {
            Log.e("MainActivity", sqlEx.getMessage(), sqlEx);
        }

Is there a change that needs to be made so that the output .csv file matches the desired output?

0

1 Answer 1

0

The solution is nice and quick and requires a very small change to one line for the original code.

The line:

CSVWriter csvWrite = new CSVWriter(new FileWriter(file));

just needed to be rewritten as:

CSVWriter csvWrite = new CSVWriter(new FileWriter(file), CSVWriter.NO_QUOTE_CHARACTER, "\r\n");

for it work as needed for me.

Some explanation from a bit of research. According to the CSVWriter documentation:

NO_QUOTE_CHARACTER is as the name suggests, suppresses all quotation marks.

From the Constant Field Values page, "\r\n" or "\n" or even DEFAULT_LINE_END can be used as a default line terminator.

The observed effect of including both of these eliminated all quotation marks and separated each row.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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