How to export room database as excel/csv file?

80 Views Asked by At

I am developing an app where I want to export the database tables as an excel/csv file.

Here is my current code:

val dbhelper = DBHelper()
val exportDir = File(getExternalStorageDirectory(), "")
if (!exportDir.exists()) {
    exportDir.mkdirs()
}

val file = File(exportDir, "csvname.csv")
try {
    file.createNewFile()
    val csvWrite = CSVWriter(FileWriter(file))
    val db = dbhelper.readableDatabase
    val curCSV = db.rawQuery("SELECT * FROM TableName", null)
    csvWrite.writeNext(curCSV.columnNames)
    while (curCSV.moveToNext()) {
        //Which column you want to export
        val arrStr = arrayOf(curCSV.getString(0), curCSV.getString(1), curCSV.getString(2))
        csvWrite.writeNext(arrStr)
    }
    csvWrite.close()
    curCSV.close()
} catch (sqlEx: java.lang.Exception) {
    Log.e("MainActivity", sqlEx.message, sqlEx)
}

Now, I am currently facing an error that says the table I indicated in the rawQuery() does not exist. I tried to download the database and view it in DB Browser and I can see the table.

Here is the error I am encountering:

android.database.sqlite.SQLiteException: no such table: TableName (code 1): , while compiling: SELECT * FROM TableName

Upon checking the database name, it seems like DBHelper() has a default value of keystore.db

How can I change the default value of the database name that is being called by DBHelper()?

0

There are 0 best solutions below