Search code examples
androidcsvcursornewlineresultset

In Android how to append a new line to .CSV file with a Cursor


I've been working this now for quite some time and the furthest I can get is to write the entire query from the DB to the .CSV file on one long line.

When I use writeNext(string[]) with the code below the .csv is written on one long line.

//Export the orders in the database to a CSV file.  Can be transferred from device either by USB or bluetooth
public void exportOrders(View view)
{
    try
    {
        CSVWriter writer;
        writer = new CSVWriter(new FileWriter("/sdcard/orders.csv"), ',');
        writer.writeNext(cursor.getColumnNames()); //Write the column headings first before the looping starts
        //Loop through all results (use row count of table)
        for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext())
        {
            String[] entries = (cursor.getString(0)+ "," +cursor.getString(1)+ "," +cursor.getString(2)+ "," +cursor.getString(3)
                    + "," +cursor.getString(4)).split(","); //Split the string by the delimiter
            writer.writeNext(entries); //Write current row of DB to file
            writer.flush(); //Flush the stream
        }
        Toast.makeText(this, "Orders exported to .CSV successfully!", Toast.LENGTH_SHORT).show();
        writer.close();
    }
    catch (Exception erMsg)
    {
        Toast.makeText(this, erMsg.toString(), Toast.LENGTH_LONG).show();
        erMsg.printStackTrace();
    }
}

From what I am reading, this seems to be the way to do it, but I don't see how a new line could be generated from that code? Is there a way to use the Cursor with a new line, or is it standard to use a ResultSet and writeAll(result)?


Solution

  • The resolution to doing this is to declare the CSVWriter with the correct arguments. Here is the new constructor:

    writer = new CSVWriter(new FileWriter("/sdcard/orders.csv"), ',',  CSVWriter.NO_QUOTE_CHARACTER, CSVWriter.DEFAULT_ESCAPE_CHARACTER, "\r\n");
    

    This will allow for a new line to be created for every row. To be sure this works, use "\r\n" instead of just "\n" as some editors don't recognize "\n".