Search code examples
javaandroidconstructorsuperandroid-fragment-manager

Cannot resolve method super() error in fragmentmanager Android


I am not a Java coder but trying to build an app while trying to learn Java along the way. I am trying to add 2 fragments one is the login fragment and one is the register fragment but while using super constructor I am facing cannot resolve error. Could anyone suggest what I am doing wrong?

I get that super is used for accessing the parent class constructor which in my case is not empty.

Following is the MainActivity code:

public class MainActivity extends FragmentActivity
{

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ViewPager2 viewPager = findViewById(R.id.viewPager);

        AuthenticationPagerAdapter pagerAdapter = new AuthenticationPagerAdapter(getSupportFragmentManager());
        pagerAdapter.addFragment(new fragment_login());
        pagerAdapter.addFragment(new fragment_register());
        viewPager.setAdapter(pagerAdapter);
    }

    public static class AuthenticationPagerAdapter extends FragmentStateAdapter
    {
        private ArrayList<Fragment> fragmentList = new ArrayList<>();

        public AuthenticationPagerAdapter(FragmentManager fragmentActivity)
        {
            super(fragmentActivity);
        }

        public Fragment getItem(int i)
        {
            return fragmentList.get(i);
        }

        public int getCount()
        {
            return fragmentList.size();
        }

        void addFragment(Fragment fragment) {
            fragmentList.add(fragment);
        }

        @NonNull
        @Override
        public Fragment createFragment(int position)
        {
            return null;
        }

        @Override
        public int getItemCount()
        {
            return 0;
        }
    }
}

Solution

  • Using the super() in a constructor you are trying to call the constructor of the parent class.

    In this case the FragmentStateAdapter has 3 constructors:

    FragmentStateAdapter(FragmentActivity fragmentActivity)
    FragmentStateAdapter(Fragment fragment)
    FragmentStateAdapter(FragmentManager fragmentManager, Lifecycle lifecycle)
    

    In your case you have:

    public AuthenticationPagerAdapter(FragmentManager fragmentActivity)
    

    and super(FragmentManager); doesn't match any super constructor.

    You can use something like:

    public AuthenticationPagerAdapter(FragmentActivity fragmentActivity) {
            super(fragmentActivity);
        }
    
    public AuthenticationPagerAdapter(FragmentManager fragmentManager,Lifecycle lifecycle) {
            super(fragmentManager, lifecycle);
        }