Home > Software design >  intent.getStringExtra() returns null
intent.getStringExtra() returns null

Time:02-23

Im trying to send data class object to another activity with intent but it returned null so i tried sending simple string but it still returns null, i couldn't find what is the problem. Here is my code

code in LoginScreen.kt

                val intentUser = Intent(this@LoginScreen,HomeActivity::class.java)
                val string = "intent"
                intentUser.putExtra("intent",string)
                startActivity(intentUser)
                finish()

and code in my HomeActivity

        val intentUser = Intent()
        var string = intentUser.getStringExtra("intent")
        Log.e("Intent: ",string.toString())

result

2022-02-23 14:25:09.139 11365-11365/com.scibilisim.d_forceandroid E/Intent:: null

CodePudding user response:

Please try this in your LoginScreen.kt:

val intentUser = Intent(this@LoginScreen,HomeActivity::class.java)
val string = "intent"
intentUser.putString("intent",string)
startActivity(intentUser)
this.finish()

and in your HomeActivity:

val string = intent!!.getStringExtra("intent")

The error is that you are instantiating a new Intent object.

CodePudding user response:

in HomeActivity you are initializing intent as

intent = Intent()

This actually initializes the intent with a new intent object. That is not desired behavior, to achieve desired behavior use getIntent() instead of Intent().

  • Related