androidandroid-studioandroid-fragmentskotlinandroid-tabbed-activity

Kotlin: setOnClickListener on Fragment Crashes app


I have a MainActivity with a button that calls on a tabbedActivity with FragmentOneActivity and fragment_one.xml. I have placed my button in the fragment_one.xml and perform a Toast on FragmentOneActivity. Here's my code:

class Anct3bActivity : Fragment() {
override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View {
    val v : View = inflater.inflate(R.layout.fragment_anct3b, container, false)

    calculateNutCountButton.setOnClickListener {
        Toast.makeText(
            activity,"Success.",
            Toast.LENGTH_SHORT).show()
    }
    return v
}

}

My application starts fine but when a click the button that calls on tabbedActivity, my application crashes. However, when I delete the calculateButton.setOnClickListener from FragmentOneActivity the tabbedActivity works fine.

I also tried placing the calculateButton.setOnClickListener on tabbedActivity but it still crashes.

Its my first time venturing into tabbed activities but I can't someone use a setOnClickLIstener.

Kindly walk me through this. Thanks!

Logcat:

On FragmentOneActivity:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

On tabbedActivity

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.demicode.ccdofieldkit/com.a.fr.meActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

Solution

  • Set your on click listener in onViewCreated, in onCreateView you are calling onClick listener before the view could set.

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        calculateNutCountButton.setOnClickListener {
            Toast.makeText(
                activity,"Success.",
                Toast.LENGTH_SHORT).show()
        }
    }