'image slider works in activity but not in fragment

the code from this video https://www.youtube.com/watch?v=1AS5HcXPpqk works fine in activity, but when i try to implement it in fragment it crashes.

java code and xml file respectively

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

    ImageSlider imageSlider = (ImageSlider) getView().findViewById(R.id.slide);
    List<SlideModel> slideModels = new ArrayList<>();
    slideModels.add(new SlideModel(R.drawable.ic_launcher_background, "Image1"));
    slideModels.add(new SlideModel(R.drawable.ic_launcher_background, "Image2"));
    slideModels.add(new SlideModel(R.drawable.ic_launcher_background, "Image3"));
    imageSlider.setImageList(slideModels, true);


    return view;
    }

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:background="#E4E3E3">


    <com.denzcoskun.imageslider.ImageSlider
    android:id="@+id/slide"
    android:layout_width="match_parent"
    android:layout_height="250dp"
    app:auto_cycle="true"
    app:delay="0"
    app:period="1000"
    app:corner_radius="20"
    />

    </RelativeLayout>


Solution 1:[1]

Don't

ImageSlider imageSlider = (ImageSlider) getView().findViewById(R.id.slide);

Do

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

    View view = inflater.inflate(R.layout.fragment_facts, container, false);
    ImageSlider imageSlider = (ImageSlider) view.findViewById(R.id.slide);

Solution 2:[2]

Change this line

ImageSlider imageSlider = (ImageSlider) getView().findViewById(R.id.slide);

to

ImageSlider imageSlider = (ImageSlider) getActivity().findViewById(R.id.slide);

You need to pass correct context getActivity()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 IntelliJ Amiya
Solution 2 Quick learner