skip to Main Content

I was just making a simple program that sends string that’s typed in an EditText into a TextView in another activity, I’m a beginner and was following a kotlin tutorial on the internet, the program would crash whenever it gets the string from the 1st activity, The code of the 1st activity looks like this:

class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    findViewById<Button>(R.id.button).setOnClickListener {

        val message: String? = findViewById<EditText>(R.id.sameer).text.toString()
        val kash = Intent(this, kos::class.java)
        intent.putExtra("sameer", message)
        startActivity(kash)



    }
}
}

and the code for the 2nd activity goes like this:

class kos: AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {

    super.onCreate(savedInstanceState)
    setContentView(R.layout.kos)
    val kanye: Bundle? = intent.extras
    val shaheer = kanye!!.getString("sameer")
    Toast.makeText(this, shaheer , Toast.LENGTH_SHORT)
    findViewById<TextView>(R.id.UserisHambola).text = shaheer

}




}

I’ve tried to check when does the error start to happen, it appears that it starts to happen after declaring variable "shaheer" in the 2nd activity, if I delete that code with all the other codes after it, the program doesn’t crash, I don’t know why does this crash happen, Thank you for your time <3

2

Answers


  1. Try to replace kanye!!.getString("sameer") with kanye?.getStringExtra("sameer") ?: "no data". This way the program will not crash if no value is passed under "sameer" key and the default "no data" will be stored to val shaheer. If you see no data in the toast, you passed the variable between activities incorrectly.

    Login or Signup to reply.
  2. You do this in MainActivity:

        val kash = Intent(this, kos::class.java)
        intent.putExtra("sameer", message)
        startActivity(kash)
    

    You put the extra with the key "sameer" into the Intent referenced by the variable intent. You probably want to put the extra into the Intent referenced by the variable kash. Try this instead:

        val kash = Intent(this, kos::class.java)
        kash.putExtra("sameer", message)
        startActivity(kash)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search