Search code examples
androidkotlinandroid-intentandroid-activity

Data not being passed between activities through Intent


//In MainActivity
binding.doneButton.setOnClickListener {
            checkValid()
            if (valid){
                val bmi: Double = calculateBmi().round(1)
                val bmr: Double = calculateBmr().round(2)
                Intent(this, DailyActivity::class.java).also{
                    intent.putExtra("EXTRA_BMI", bmi)
                    intent.putExtra("EXTRA_BMR", bmr)
                    startActivity(it)
                }

            }
        }
//In DailyActivity
var bmi = intent.getDoubleExtra("EXTRA_BMI", 0.0)
var bmr = intent.getDoubleExtra("EXTRA_BMR", 0.0)

I want to pass these two Double values bmi and bmr from my MainActivity to DailyActivity. I checked the values and they work fine inside MainActivity. But when I try to pass them to DailyActivity, the default value of 0.0 is being used. I tried intent?.extras?.getDouble("EXTRA_BMI") as well but that's not working either. How can I fix this?

(Btw round is an extension function I found on SO. It works fine. That's not why the code isn't working)


Solution

  • Inside your also block, by calling intent.putExtra(...) you are altering the current Activity's intent (the one you would access with this@MainActivity.intent), not the one you just created.

    What you want is

    Intent(this, DailyActivity::class.java).also{
        it.putExtra("EXTRA_BMI", bmi)
        it.putExtra("EXTRA_BMR", bmr)
        startActivity(it)
    }