我的第一个问题是-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
答案 0 :(得分:2)
只需这样做
val s = cursor!!.getString(j)
if(s == null)
bw.write("whatever string value you want here")
else
bw.write(s)