I'm trying to save an array list of messages to a file. When I try to make it, the first record don't save.
My code is:
val chatfile = File(MyApp.applicationContext().filesDir, "${user_id}-${conversacion.sender}-short.json")
if (chatfile.exists()) {
val contents = chatfile.readText()
val array: List<Message> =
gson.fromJson(contents, kotlin.Array<Message>::class.java).toList()
val arrayList = ArrayList(array.toList())
arrayList.add(0, Message(conversacion.unique_id, conversacion.sender, conversacion.receiver, conversacion.nickname, conversacion.message, conversacion.send_at, false, conversacion.image, conversacion.latitude, conversacion.longitude, conversacion.viewType, conversacion.messageType))
val json: String = gson.toJson(arrayList.filterNotNull()).replace("\n", "
")
chatfile.writeText(json)
} else {
val array: List<Message> = emptyList()
val arrayList = ArrayList(array.toList())
arrayList.add(Message(conversacion.unique_id, conversacion.sender, conversacion.receiver, conversacion.nickname, conversacion.message, conversacion.send_at, false, conversacion.image, conversacion.latitude, conversacion.longitude, conversacion.viewType, conversacion.messageType))
val json: String = gson.toJson(arrayList.filterNotNull()).replace("\n", "
")
chatfile.writeText(json)
}
The part of (if chatfile.exists) save the record, but the "else" part just creates an empty file and don't save the record.
Am I doing something wrong?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…