Home > Net >  Retrieving a boolean from another activity causes a NullPointerException (Kotlin)
Retrieving a boolean from another activity causes a NullPointerException (Kotlin)

Time:07-25

As I said in the title, I'm trying to retrieve a boolean from the intent. Basically what I'm trying to do is going to activity2, there, I click a button and clicking that will make me jump into the main activity and send a boolean with the value "true" with the intent, and retrieve it in the main activity.

This is the code in the main activity:

class MainActivity : AppCompatActivity() {

var a = intent.getBooleanExtra("a", false)
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    var btn: Button = findViewById(R.id.button)

    btn.setOnClickListener {
        var intent = Intent(this@MainActivity, MainActivity2::class.java)
        startActivity(intent)
    }

    if(a) {
        Toast.makeText(this, "true", Toast.LENGTH_LONG).show()
    }

}

}

This is the code in the second activity

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

    var btn2: Button = findViewById(R.id.button2)

    btn2.setOnClickListener {
        var intent = Intent(this@MainActivity2, MainActivity::class.java)
        intent.putExtra("a", true)
        startActivity(intent)
    }
}

}

What should I change?

CodePudding user response:

You assign a immediately as soon as a new instance of the MainActivity is created. At that point it's possible that you boolean extra hasn't been set yet.

You can either make it lazy or retrieve it inside your onCreate function.

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    val a = intent.getBooleanExtra("a", false)
    ...

CodePudding user response:

Please write below line inside onCreate method, in your current code you have written it outside of onCreate method.

var a = intent.getBooleanExtra("a", false)
  • Related