Search code examples
javaandroidandroid-activitynullpointerexception

How do I set a ClickListener in a Activity to a Button that belongs to a Fragment? (Android studio Java)


i need some help. I'm making an app on android studio and I have a Button initialized in a Fragment. I need to call this button in another Activity and set a click listener on it.

The problem is that when I do this I get the .NullPointerExceptionError and it says that the value of the object is null.

Now i tried to initialize the button in both my fragment and Activity but I keep getting that error and the app crashes.

I need some help to call this button from the Fragment. Maybe my question is similar to some other but it's hours that I'm searching a solution to this problem and I found nothing.

Thanks in advance for all your help


Solution

  • Since the button is part of the fragment, it only fits that any interactions/modifications to the button be defined in the Fragment's scope itself.

    There are 2 ways to go about it:

    1. Create the click listener in the Fragment itself and navigate to another activity from there.

    2. Create an interface which your activity implements and the fragment has an instance of that interface. On the button click, call the interface's method. That would give you control in the activity which is hosting the fragment.

      MyActivity extends AppCompatActivity implements MyClickListener {
      
          void onMyButtonClick() {
             // Navigate to another activity here
          }
      }
      
      
      MainFragment extends Fragment {
      
          private MyClickListener listener;
      
          void onAttach(Context context) {
              listener = (MyClickListener) context;
              // Now call listener.onMyButtonClick() from button's on click listener.
          }
      }
      
      interface MyClickListener {
          void onMyButtonClick();
      }