Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Snackbar action gets null pointer after moving to another fragment

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()
}

>Solution :

 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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading