Search code examples
android-studiokotlinparcelable

How to pass string from activity to another activity in kotlin


I am trying to pass over a text to my second activity but it does not seem to be working correctly. For my main activity i have a a textview and the text says 'Cat'. When the image on the first activity is pressed on, I want "Cat" to be passed over to the second activity. The second activity's textview should also display "Cat", however when I do this, it will show up as "Info(name=Cat)" rather then just "Cat".

I am not sure where i went wrong.

This is my main activity

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val image = findViewById<ImageView>(R.id.imageView)
        val text = findViewById<TextView>(R.id.textView)

        image.setOnClickListener {
            val intent= Intent(this, MainActivity2::class.java).apply {

                putExtra("name", Info("Cat"))
            }
            startActivity(intent)
        }
    }
}

My parcelable class

@Parcelize
data class Info(val name : String) : Parcelable {
}

This is my second activity

class MainActivity2 : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main2)

        val info = intent.getParcelableExtra<Info>("name")

        val name = findViewById<TextView>(R.id.textView2)

        name.text = info.toString()

    }
}

Solution

  • You're converting the whole Info data class to its string representation. You only want the name property from the data class.

    name.text = info.name