Search code examples
androidkotlindata-classkotlinx.serialization

java.io.NotSerializableException with serializable data class in Kotlin (kotlinx.serialization)


I'm facing java.io.NotSerializableException when trying to writeObject and object of a data class into an ObjectOutputStream. Following is the main activity function of my project :

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        debug()
    }
    fun debug() {
        val oos = ObjectOutputStream(ByteArrayOutputStream())
        val obj = BaseElement("HELLO WORLD")
        try{
            oos.writeObject(obj)
        }
        catch(e : Exception) {
            Log.d("mydebug", e.stackTraceToString())
        }
    }
}

The BaseElement class can be found here :

import kotlinx.serialization.Serializable

@Serializable
data class BaseElement(var sentence : String)

The stacktracke is as following :

java.io.NotSerializableException: com.example.myproject.model.BaseElement
        at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1240)
        at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:354)
        at com.example.myproject.MainActivity.debug(MainActivity.kt:29)
        at com.example.myproject.MainActivity.onCreate(MainActivity.kt:17)
        at android.app.Activity.performCreate(Activity.java:8130)
        at android.app.Activity.performCreate(Activity.java:8110)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1343)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3781)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3977)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:109)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2374)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loopOnce(Looper.java:233)
        at android.os.Looper.loop(Looper.java:344)
        at android.app.ActivityThread.main(ActivityThread.java:8248)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:589)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1071)

Someone please help me understand the solution to this issue.


Solution

  • Implement the serializable interface

    import kotlinx.serialization.Serializable
    
    
    data class BaseElement(var sentence : String) : Serializable