Android sqllite table to csv

by admin on June 10, 2014

to convert any table to csv use the code below.


public boolean createCsvSaveToFile(Cursor cursor, String fileName) throws IOException {
String csv = "";
int colunmCount = cursor.getColumnCount(), i;
//check if extarnal drive is readerble
if (!isExternalStorageWritable()) {
fileError = "can not save to external storage";
fileinfo = "Please mount your SD card";
return false;
}
//create CSV
for (i = 0; i < colunmCount; i++) {//GET COLUNM NAMES
csv += QUOTES + cursor.getColumnName(i).toString() + QUOTES + INNER_DELIMITER;
}
csv = csv.replaceAll(",$", "");
csv += LINE_END;
if (cursor.moveToFirst()) {
do {
for (i = 0; i < colunmCount; i++) {//GET COLUNM values
csv += QUOTES + cursor.getString(i) + QUOTES + INNER_DELIMITER;
}
csv = csv.replaceAll(",$", "");
csv += LINE_END;
} while (cursor.moveToNext());
}
//save file
File file = getDataDir(fileName);
FileOutputStream out = new FileOutputStream(file);
out.write(csv.getBytes());
out.flush();
out.close();
return true;
}

 

private boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}

/* Create data dir or return it */
private File getDataDir(String tableCsv) throws IOException {
// Get the directory for the app data directory.
String f = tableCsv + ".csv";
File dataDirectory = new File(DATA_DIRECTORY, f);
if (!dataDirectory.exists()) {
if (!dataDirectory.createNewFile()) {
Log.e("getStorageDir", "file " + f + " not created");
fileError = "file " + f + " not created";
fileinfo = "unable to create backup file";
return null;
}
}
return dataDirectory;
}

just create a cursor with the appropriate data and call the function

you may set the file name to match the table name

look for code on how to add records into the android database from CSV here

Leave a Comment