I am new to android Kotlin. I am trying to Pass object from one activity to another activity I got stuck,
MyClass :
data class MyPojo(val name: String, val age: String) : Serializable
FirstActivity :
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val editTextName = findViewById<EditText>(R.id.EditName)
val editTextAge = findViewById<EditText>(R.id.EditAge)
val button = findViewById<Button>(R.id.ButtonSend)
button.setOnClickListener {
val object1 = MyPojo(editTextName.text.toString(),editTextAge.text.toString())
val intent = Intent(this,Main2Activity::class.java)
intent.putExtra("Obj",object1)
startActivity(intent)
}
}
}
SecondActivity :
class Main2Activity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main2)
val obj :MyPojo = intent.getSerializableExtra("obj") as MyPojo
val textView : TextView = findViewById(R.id.textViewName)
val textViewAge : TextView = findViewById(R.id.textViewAge)
textView.setText(obj.name)
textViewAge.setText(obj.age)
}
}
Error :
6-28 19:35:58.625 22192-22192/com.example.evalai.passingobjecttoactivity E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.evalai.passingobjecttoactivity, PID: 22192 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.evalai.passingobjecttoactivity/com.example.evalai.passingobjecttoactivity.Main2Activity}: kotlin.TypeCastException: null cannot be cast to non-null type com.example.evalai.passingobjecttoactivity.MyPojo at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2442) at android.app.ActivityThread.access$800(ActivityThread.java:156) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1351) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:211) at android.app.ActivityThread.main(ActivityThread.java:5371) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:945) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:740) Caused by: kotlin.TypeCastException: null cannot be cast to non-null type com.example.evalai.passingobjecttoactivity.MyPojo at com.example.evalai.passingobjecttoactivity.Main2Activity.onCreate(Main2Activity.kt:14) at android.app.Activity.performCreate(Activity.java:5990) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2332)