invoke a button click event from main activity when the button is inside another fragment

52 views Asked by At

I am trying to write a setOnClickListener to a button which is inside an other fragment called InsertFragment from my main activity

I am new to android development so that I can't understand why I am getting this error. I have tried to use setContentView(R.layout.fragment_insert) but that didn't work

my fragment will be called when I choose the relevant fragment from the menu bar

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

This is the error I am getting. Please correct my mistakes. Thanks in advance

1

There are 1 answers

3
Barungi Stephen On

Make sure your Button is declared and Initialized

something Like

Button addButton = findViewById(R.id.add_button);