我正在尝试将本地json存储引入到我正在制作的应用程序中。我以前使用过这种json存储方法,但从未遇到过这些错误; Type mismatch: inferred type is Context but Path! was expected
以及 Type mismatch: inferred type is String but LinkOption! was expected
在context和json文件上,错误如下所示:
constructor (context: Context) {
this.context = context
if (exists(context, JSON_FILE)) {
deserialize()
}
}
以下是课程:
package ie.wit.models
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import org.jetbrains.anko.AnkoLogger
import java.nio.file.Files.exists
import kotlin.random.Random
import ie.wit.helpers.**/
import android.content.Context
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import org.jetbrains.anko.AnkoLogger
import ie.wit.helpers.*
import java.nio.file.Files.exists
import java.util.*
val JSON_FILE = "bookings.json"
val gsonBuilder = GsonBuilder().setPrettyPrinting().create()
val listType = object: TypeToken<ArrayList<ValetModel>>(){}.type
fun generateRandomId(): Long {
return Random().nextLong()
}
class ValetJSONStore: ValetStore, AnkoLogger{
val context: Context
var bookings = mutableListOf<ValetModel>()
constructor (context: Context) {
this.context = context
if (exists(context, JSON_FILE)) {
deserialize()
}
}
override fun findAll(): List<ValetModel> {
return bookings
}
override fun create(valet: ValetModel) {
valet.id = generateRandomId()
bookings.add(valet)
serialize()
}
override fun update(valet: ValetModel) {
val bookingsList = findAll() as ArrayList<ValetModel>
var foundBooking: ValetModel? = bookingsList.find{p -> p.id == valet.id}
if(foundBooking != null){
foundBooking.brand = valet.brand
foundBooking.model = valet.model
foundBooking.numberPlate = valet.numberPlate
foundBooking.date = valet.date
}
serialize()
}
override fun delete(valet: ValetModel) {
bookings.remove(valet)
serialize()
}
private fun serialize(){
val jsonString = gsonBuilder.toJson(bookings, listType)
write(context, JSON_FILE, jsonString)
}
private fun deserialize() {
val jsonString = read(context, JSON_FILE)
bookings = Gson().fromJson(jsonString, listType)
}
}
1条答案
按热度按时间i1icjdpr1#
解释为什么会出现这样的错误:如果您检查文档
exists(..)
为了import java.nio.file.Files.exists
它期待着Path
而不是一个Context
:可能在其他实现了相同功能的类中,可能您正试图使用
exists(..)
从其他不同的地方导入的方法java.nio.file.Files.exists
?要检查该文件是否存在,您有许多选项,但现在我可以列出两个选项,其中一个您已经尝试使用(exists(…)可从api 26获得):