Search code examples
javaandroidandroid-fragmentactivity

When you open a new activity in a fragment the app stops


The problem that Teno I want to use an intro slide in my app through fragments and the third fragment I want to put a button that leads to another activity and in Android studio the code does not make any error but when I run the app and click the app button It stops what is it?

public ThirdFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_third, container, false);


    viewPager = getActivity().findViewById(R.id.viewPager);
    back1 = view.findViewById(R.id.slideThereback);

    back1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            viewPager.setCurrentItem(1);
        }
    });

    //The TextView  "Done " is the one I want to click on the Take me to another activity and that up to now gives me an error to run in the emulator

    done = view.findViewById(R.id.Done);
    done.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent myIntent = new Intent(getActivity(), MenuP.class);
            startActivity(myIntent);

        }
    });

    return view;
}

I hope I can provide the code or say my error to open a new activity in a fragment and not close the app to Ejecutarce on a mobile device


Solution

  • Use the below code in your onClick() method.

        Intent myIntent = new Intent(getActivity(), MenuP.class);
        getActivity().startActivity(myIntent);