0

Im trying to run an activity from a button press in a fragment, however the app crashes when the button is pressed.

public class FitnessFragment extends Fragment {

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        View root = inflater.inflate(R.layout.fragment_fitness, container, false);

        Button btn1 = (Button) root
                .findViewById(R.id.trackCalories);

        btn1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(getActivity(), video_activity.class);
                ((MainActivity) getActivity()).startActivity(intent);

            }
        });

        return root;
    }
}

I'm currently struggling to grasp the concept of launching activities from fragments, any help would be appreciated.

Leonardo
  • 2,439
  • 33
  • 17
  • 31
JF123
  • 13
  • 3
  • Does this answer your question? [Unfortunately MyApp has stopped. How can I solve this?](https://stackoverflow.com/questions/23353173/unfortunately-myapp-has-stopped-how-can-i-solve-this) – a_local_nobody Feb 11 '22 at 13:14
  • why are you using `findViewById` with viewbinding ? seems more likely that you're struggling with some other basic concepts which are holding you back – a_local_nobody Feb 11 '22 at 13:15
  • @a_local_nobody could you explain? – JF123 Feb 11 '22 at 13:18
  • there's nothing to explain, like i said, `why are you using findViewById with viewbinding ?` what does viewbinding do ? – a_local_nobody Feb 11 '22 at 13:20
  • @a_local_nobody I've updated the code on the post, the problem persists, – JF123 Feb 11 '22 at 13:32
  • because, without knowing the cause of the problem, you and all of us here are just guessing what's wrong, so use the first link i sent you and find your stack trace, then we don't have to guess what's wrong – a_local_nobody Feb 11 '22 at 13:34

2 Answers2

0

You can simply do like this:

 btn1.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
      startActivity(new Intent(requireActivity(), video_activity.class)) 
    }
});
Rudra Rokaya
  • 637
  • 1
  • 5
  • 9
0
btn1.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
      startActivity(new Intent(requireContext(), video_activity.class)) 
    }
});
Tarif Chakder
  • 1,708
  • 1
  • 11
  • 10