Ramz
Ramz

Reputation: 935

ClassCastException : Main Activity must implement onFragmentInteractonListener

I got the ClassCastException when i try to implement onClick for navigation drawer items.

Please find the code below.

I am not able to figure out where it went wrong

MainActivity:

public class MainActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener {

Toolbar toolbar;
ViewPager pager;
ViewPagerAdapter adapter;
SlidingTabLayout tabs;
CharSequence Titles[] = {"CITY", "GO", "NEAR"};
int Numboftabs = 3;
private FragmentDrawer drawerFragment;
private Handler mHandler;

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


    // Creating The Toolbar and setting it as the Toolbar for the activity

    toolbar = (Toolbar) findViewById(R.id.app_bar);
    setSupportActionBar(toolbar);


    // Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
    adapter = new ViewPagerAdapter(getSupportFragmentManager(), Titles, Numboftabs);

    // Assigning ViewPager View and setting the adapter
    pager = (ViewPager) findViewById(R.id.pager);
    pager.setAdapter(adapter);

    // Assiging the Sliding Tab Layout View
    tabs = (SlidingTabLayout) findViewById(R.id.tabs);
    tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width

    // Setting Custom Color for the Scroll bar indicator of the Tab View
    tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
        @Override
        public int getIndicatorColor(int position) {
            return getResources().getColor(R.color.tabsScrollColor);
        }
    });

    // Setting the ViewPager For the SlidingTabsLayout
    tabs.setViewPager(pager);


    drawerFragment = (FragmentDrawer)
            getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
    drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), toolbar);
    drawerFragment.setDrawerListener(this);


    // display the first navigation drawer view on app launch
    displayView(0);

}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@Override
public void onDrawerItemSelected(View view,  final int position) {
displayView(position);

}
private void displayView(int position) {
    Fragment fragment = null;
    String title = getString(R.string.app_name);
    switch (position) {
        case 0:
            fragment = new ContactFragment();
            title = getString(R.string.nav_item_contact);

            break;
        case 1:
            fragment = new MyLocation();

            title = getString(R.string.nav_item_myloc);
            break;

        case 2:
            fragment = new TermsandCondition();
            title = getString(R.string.nav_item_terms);
            break;

        case 3:
            fragment = new UpgradePlan();
            title = getString(R.string.nav_item_upgrade);
            break;
        case 4:
            fragment = new Aboutus();
            title = getString(R.string.nav_item_about);


            break;


        default:
            break;
    }
    if (fragment != null) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        //   fragmentTransaction.setCustomAnimations(android.R.anim.fade_in,android.R.anim.fade_out,android.R.anim.fade_in,android.R.anim.fade_out);
        fragmentManager.addOnBackStackChangedListener(null);
        fragmentTransaction.replace(R.id.container_body, fragment);
        fragmentTransaction.commit();

        // set the toolbar title
        // actionBar.setTitle(Html.fromHtml("<font color='#ff0000'>ActionBartitle </font>"));
        getSupportActionBar().setTitle(Html.fromHtml("<font color='#000000'>" + title + " </font>"));
        //  final Drawable upArrow = getResources().getDrawable(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
        //  upArrow.setColorFilter(getResources().getColor(R.color.grey), PorterDuff.Mode.SRC_ATOP);
        // getSupportActionBar().setHomeAsUpIndicator(upArrow);


    }
}
}

ContactFragment:

public class ContactFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;

private OnFragmentInteractionListener mListener;


// TODO: Rename and change types and number of parameters
public static ContactFragment newInstance(String param1, String param2) {
    ContactFragment fragment = new ContactFragment();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}

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

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }
}

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

// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
    if (mListener != null) {
        mListener.onFragmentInteraction(uri);
    }
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        mListener = (OnFragmentInteractionListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement OnFragmentInteractionListener");
    }
}

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}

public interface OnFragmentInteractionListener {
    // TODO: Update argument type and name
    public void onFragmentInteraction(Uri uri);
}

}

Logcat:

 java.lang.ClassCastException:    keleno.example.ramz.mapper_city.MainActivity@21c6ea2b must implement   OnFragmentInteractionListener
10-16 11:28:13.664 28882-28882/keleno.example.ramz.mapper_city E/AndroidRuntime:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2339)
10-16 11:28:13.664 28882-28882/keleno.example.ramz.mapper_city E/AndroidRuntime:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2413)
10-16 11:28:13.664 28882-28882/keleno.example.ramz.mapper_city E/AndroidRuntime:     at android.app.ActivityThread.access$800(ActivityThread.java:155)
10-16 11:28:13.664 28882-28882/keleno.example.ramz.mapper_city E/AndroidRuntime:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1317)
10-16 11:28:13.664 28882-28882/keleno.example.ramz.mapper_city E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:102)
10-16 11:28:13.664 28882-28882/keleno.example.ramz.mapper_city E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:135)
10-16 11:28:13.664 28882-28882/keleno.example.ramz.mapper_city E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5343)
10-16 11:28:13.664 28882-28882/keleno.example.ramz.mapper_city E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Native Method)
10-16 11:28:13.664 28882-28882/keleno.example.ramz.mapper_city E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Method.java:372)
10-16 11:28:13.664 28882-28882/keleno.example.ramz.mapper_city E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)
10-16 11:28:13.664 28882-28882/keleno.example.ramz.mapper_city E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)
10-16 11:28:13.664 28882-28882/keleno.example.ramz.mapper_city E/AndroidRuntime:  Caused by: java.lang.ClassCastException: keleno.example.ramz.mapper_city.MainActivity@21c6ea2b must implement OnFragmentInteractionListener
10-16 11:28:13.664 28882-28882/keleno.example.ramz.mapper_city E/AndroidRuntime:     at keleno.example.ramz.mapper_city.fragment.ContactFragment.onAttach(ContactFragment.java:85)

Any help is appreciated!!

Upvotes: 0

Views: 1615

Answers (2)

Hari Krishnan
Hari Krishnan

Reputation: 6312

You are using interfaces within a fragment to pass the values(It may be a view in the fragment that you click) from your fragment to activity.

If you don't need to pass any such values from fragment to your activity, you can remove them, else you can pass the values from the fragment to a method in its interface and you can override that method in your activity to access that parameters.Here since you dont need to pass anything from your fragment to activity, you can remove the interface from your fragment. It is the same case for all your fragments.

Upvotes: 0

Satyen Udeshi
Satyen Udeshi

Reputation: 3243

Solution

Add this to your MainActivity

public class MainActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener,ContactFragment.OnFragmentInteractionListener {

and override the method in public void onFragmentInteraction(Uri uri) in MainActivity

This error occurs because you are not implementing the interface in the Activity hosting the Fragments. You will need to implement interface of all the Fragments.

Explanation

You can see this in your onAttach() of your Fragment where you write a condition to see if the Hosting Activity has implemented the underlying Fragment Interface.

The ideal advice would be to remove the interface from your fragment if you are not going to use for callbacks and other stuff or else go on and implement the interfaces.

You can ask if you need any further explanation.

and yes would like to suggest to read the following to get a broader idea of Fragments stuff, Fragment Basics

Upvotes: 5

Related Questions