Android Studio: Error:(30, 24) error: incompatible types: Activity cannot be converted to Fragment

1.1k views Asked by At

Getting the below error:

"Error:(30, 24) error: incompatible types: TabMyMatesActivity cannot be converted to Fragment".

enter image description here

I'm new to android development. Initially the code works fine. But now its showing the error. Can Anyone help me with this issue?

package com.example.mmp.myapplication;

    import android.support.v4.app.Fragment;
    import android.support.v4.app.FragmentManager;
    import android.support.v4.app.FragmentStatePagerAdapter;

    //Extending FragmentStatePagerAdapter
    public class Pager extends FragmentStatePagerAdapter {

        //integer to count number of tabs
        int tabCount;

        //Constructor to the class
        public Pager(FragmentManager fm, int tabCount) {
            super(fm);
            //Initializing tab count
            this.tabCount= tabCount;
        }

        //Overriding method getItem
        @Override
        public Fragment getItem(int position) {
            //Returning the current tabs
            switch (position) {
                case 0:
                    TabMyMatesActivity tab1 = new TabMyMatesActivity();
                    return tab1;
                case 1:
                    TabRequestsActivity tab2 = new TabRequestsActivity();
                    return tab2;
                case 2:
                    TabSuggestionsActivity tab3 = new TabSuggestionsActivity();
                    return tab3;
                case 3:
                    TabContactsActivity tab4 = new TabContactsActivity();
                    return tab4;
                default:
                    return null;
            }
        }

        //Overriden method getCount to get the number of tabs
        @Override
        public int getCount() {
            return tabCount;
        }
    }
1

There are 1 answers

0
Doron Yakovlev Golani On

An Activity is not a Fragment. That is the reason for the cast failure (cast is when you convert a reference of one object type to another type).

What I suggest you do is convert the "screens" you want in the view pager from activities into fragments. If you still want to use them as activities on some cases, you should create individual activities and each of those should contain one of the fragments. This way will allow you to reuse the fragments.

So for example your code should look somewhat like this:

    @Override
    public Fragment getItem(int position) {
        //Returning the current tabs
        switch (position) {
            case 0:
                return new TabMyMatesFragment();
            ...

I suggest you read the fragment documentation before you continue so you can better understand this.