有什么办法可以将“空”值从数据库写入CSV文件?

时间:2019-09-18 08:50:44

标签: android sqlite kotlin bufferedwriter

我的第一个问题是-BufferedWriter是否能够将空值写入文件? 就我而言,我正在尝试将数据库中的每个数据导出到csv文件。数据库中有空值。我可以使用BufferedWriter导出没有空值的数据库。但不能使用null。我的问题是,是否可以使用当前代码导出包含null的数据库?这是代码。

这是出口类别-

    private fun export() {
    try {
        db=DataBaseHelper(this)
        val db=this.openOrCreateDatabase(REAL_DATABASE, Context.MODE_PRIVATE, null)
        val selectQuery=
            "Select T.date,T.location, M.barcode,M.onhand_qty,T.scanned_qty,(M.onhand_qty-T.scanned_qty) as 'DIFFERENCE' from Master M Left Outer Join transaction_table T  On M.barcode = T.barcode1  "
        val cursor=db.rawQuery(selectQuery, null)
        var rowcount: Int=0
        var colcount: Int=0

                val saveFile="/sdcard/Download/original.csv"
                val fw=FileWriter(saveFile)

                val bw=BufferedWriter(fw)
                rowcount=cursor.getCount()
                colcount=cursor.getColumnCount()

                if (rowcount>0) {
                    cursor!!.moveToFirst()

                    for (i in 0 until colcount) {
                        if (i != colcount - 1) {

                            bw.write(cursor!!.getColumnName(i) + ",")

                        } else {

                            bw.write(cursor!!.getColumnName(i))
                        }
                    }
                    bw.newLine()

                    for (i in 0 until rowcount) {
                        cursor!!.moveToPosition(i)

                        for (j in 0 until colcount) {
                            if (j != colcount - 1)
                                bw.write(cursor!!.getString(j) + ",")
                            else
                                bw.write(cursor!!.getString(j))//This is where I get the error message
                        }
                        bw.newLine()
                    }
                    bw.flush()
                }

    } catch (ex: Exception) {
        ex.printStackTrace()

    } finally {

    }

}

这是错误消息-

    java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference

1 个答案:

答案 0 :(得分:2)

只需这样做

val s = cursor!!.getString(j)
    if(s == null)
        bw.write("whatever string value you want here")
    else
        bw.write(s)