简体   繁体   中英

Configuring your build script so that you can use Kotlin serialization tools in Android Compose Project?

I would like to store and read some Kotlin data classes to and from .json files in an Android Project where I build my Activities with Compose . The class that I want to import looks like this:

import kotlinx.serialization.Serializable
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json

@Serializable
sealed class Task() {
    abstract val category: Category

    @Serializable
    data class Quiz(
        override val category : Category,
        val question: String,
        val onCorrect: String,
        val onWrong: String,
        val answers: List<String>,
        val correctPos: Int
        ) : Task()

    @Serializable
    data class Text(
        override val category: Category,
        val text: String
        ) :  Task()
}

it works without any problem after properly configuring the gradle plugin in IntelliJ . For example:

fun main() {
    val t0 : Task = Task.Text(Category.UNDEFINED, "yes pls?")
    val t1 : Task = Task.Text(Category.STANDARD, "still working?")
    val t2 : Task = Task.Quiz(Category.KNOWLEDGE, "ras", "dwa", "tre",
        mutableListOf("Test", "I Believe", "Invading Ukrain is gay"), 0)
    val list : MutableList<Task> = mutableListOf(t0, t1, t2)
    val dataT = Json.encodeToString(list)
    println(dataT)

    val dataAfter = Json.decodeFromString<MutableList<Task>>(dataT)
    println(dataAfter)
}

But I cant figure out how to get this to work using Android Studio for Android devices. When trying to do the same build it leads to this indication: warning what probably causes following error: error

Is there a way to get this to run?


If not

how else can I save polymorphic classes like this to different Lists separated by the category. SQLLight seems like a bad option to me. Because I would have to store the Tasks separated by type and not category, so all Tasks would have to be loaded to a major list before separating them again to smaller lists by the category, to then select only small parts of the lists to be later used. Or I would have to travers the whole databese once for every category. (I dont't want all tasks to be loaded all at once)

Is really the only possible way to write my own specially formatted text files? I mean have tested it and it has the same speed like reading from json, but seems not the proper way to me.

Thanks u very much in advance:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM