Home > database >  Activity not receiving the data from intent
Activity not receiving the data from intent

Time:06-17

My main activity code is here

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val button=findViewById<Button>(R.id.save)
        val loadButton=findViewById<Button>(R.id.load)
        loadButton.setOnClickListener {
            findViewById<EditText>(R.id.username).text
        }
        button.setOnClickListener {
            startActivity(Intent(this,DisplayActivity::class.java).
            putExtra("username",findViewById<TextView>(R.id.username).text))
        }
    }
}
My display activity code is here

class DisplayActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_display)
        val username=intent.getStringExtra("username").toString();
        findViewById<TextView>(R.id.username1).text=username;
    }
}

but when I click the Save Button(R.id.save) the textview is being displayed as null. Where am I going wrong?

CodePudding user response:

Using only mEditText.text returns the Editable not String, try below code:

//...
// Rest of the code above
val loadButton = findViewById<Button>(R.id.load)
        val mEditText = findViewById<EditText>(R.id.username)
        loadButton.setOnClickListener {
            startActivity(Intent(this, DisplayActivity::class.java).apply {
                putExtra("username", mEditText.text.toString()) // <- toString()
            })
        }

And get the value like this:

class DisplayActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_display)
        val username = intent.getStringExtra("username")
        findViewById<TextView>(R.id.username1).text = username
    }
}
  • Related