Home > Blockchain >  Snackbar action gets null pointer after moving to another fragment
Snackbar action gets null pointer after moving to another fragment

Time:02-11

Fragment A invokes a snackbar with an action button. When user clicks action, it starts new activity with intent. It's working fine. However, if the user moves to Fragment B while snackbar keeps appearing, then press action button, now it doesn't start new activity but crash.

enter image description here

How can I prevent crashing in this situation and make intent workable? here is my code. fragment A

binding.theButton.setOnClickListener {

    val proSnack = Snackbar.make(view!!, activity!!.getString(R.string.this_is_pro_function), Snackbar.LENGTH_LONG)
    proSnack.setAction(R.string.check, View.OnClickListener {
        activity!!.startActivity(Intent(activity, ProActivity::class.java))
    })
    proSnack.show()

    }
}

binding.backText.setOnClickListener{
    activity?.supportFragmentManager?.popBackStackImmediate()
}

CodePudding user response:

 activity!!.startActivity(Intent(activity, ProActivity::class.java))

The problem is here. You can check activity. It is null. Using !! is a bad practice. You can change it to

activity?.startActivity(Intent(activity, ProActivity::class.java))

But the activity is null. It does not open a new activity

  • Related