Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
223 views
in Technique[技术] by (71.8m points)

android - Write file in Kotlin don't save my first record

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...