java.lang.ClassCastException:fragment cannot be cast to android.support.v4.app.Fragment

22,413

Solution 1

Changing the import from android.app.Fragment to android.support.v4.app.Fragment helped me solve this. Thanks!

Solution 2

Change your import import android.app.Fragment; to import android.support.v4.app.Fragment; into TruckStatus

Solution 3

import android.support.v4.app.Fragment;

Before you do this Right click project->properties->buildpath->java build path -> libraries .. then click on add external jars

the go to

user\android-sdks\extras\android\support\v4

and select android-support-v4.jar

Share:
22,413
Jishin
Author by

Jishin

Updated on May 29, 2020

Comments

  • Jishin
    Jishin almost 4 years

    I am trying to implement Tab Navigation, I have a Container Activity that extends Fragment Activity, and this Activity creates a TabView using an ActionBar. The app will try to create three tabs and add them to the ActionBar, and I want to change the fragment depending on the TabSelection..But occured an error 07-04 12:17:33.534: E/AndroidRuntime(795): Caused by: java.lang.ClassCastException: com.freight.fragments.TruckStatus cannot be cast to android.support.v4.app.Fragment.

    TruckActivity.java

    package com.freight.activities;
    
    import java.util.Locale;
    
    import com.clacion.freightexchange.R;
    import com.clacion.freightexchange.R.drawable;
    import com.clacion.freightexchange.R.id;
    import com.clacion.freightexchange.R.layout;
    import com.clacion.freightexchange.R.menu;
    import com.clacion.freightexchange.R.string;
    import com.freight.fragments.TruckStatus;
    
    import android.app.ActionBar;
    import android.app.FragmentTransaction;
    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.support.v4.app.FragmentActivity;
    import android.support.v4.app.FragmentManager;
    import android.support.v4.app.FragmentPagerAdapter;
    import android.support.v4.app.NavUtils;
    import android.support.v4.view.ViewPager;
    import android.view.Gravity;
    import android.view.LayoutInflater;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.TextView;
    
    public class TruckActivity extends FragmentActivity implements
            ActionBar.TabListener {
    
        /**
         * The {@link android.support.v4.view.PagerAdapter} that will provide
         * fragments for each of the sections. We use a
         * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
         * will keep every loaded fragment in memory. If this becomes too memory
         * intensive, it may be best to switch to a
         * {@link android.support.v4.app.FragmentStatePagerAdapter}.
         */
        SectionsPagerAdapter mSectionsPagerAdapter;
    
        /**
         * The {@link ViewPager} that will host the section contents.
         */
        ViewPager mViewPager;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_truck);
    
            // Set up the action bar.
            final ActionBar actionBar = getActionBar();
            actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    
            // Create the adapter that will return a fragment for each of the three
            // primary sections of the app.
            mSectionsPagerAdapter = new SectionsPagerAdapter(
                    getSupportFragmentManager());
    
            // Set up the ViewPager with the sections adapter.
            mViewPager = (ViewPager) findViewById(R.id.pager);
            mViewPager.setAdapter(mSectionsPagerAdapter);
    
            // When swiping between different sections, select the corresponding
            // tab. We can also use ActionBar.Tab#select() to do this if we have
            // a reference to the Tab.
            mViewPager
                    .setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
                        @Override
                        public void onPageSelected(int position) {
                            actionBar.setSelectedNavigationItem(position);
    
                        }
                    });
    
            // For each of the sections in the app, add a tab to the action bar.
            for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
                // Create a tab with text corresponding to the page title defined by
                // the adapter. Also specify this Activity object, which implements
                // the TabListener interface, as the callback (listener) for when
                // this tab is selected.
                actionBar.addTab(actionBar.newTab()
                        .setText(mSectionsPagerAdapter.getPageTitle(i))
                        .setIcon(R.drawable.item_menu_config)                   
                        .setTabListener(this));
            }
            actionBar.setSelectedNavigationItem(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.truck, menu);
            return true;
        }
    
        @Override
        public void onTabSelected(ActionBar.Tab tab,
                FragmentTransaction fragmentTransaction) {
            // When the given tab is selected, switch to the corresponding page in
            // the ViewPager.
            mViewPager.setCurrentItem(tab.getPosition());
        }
    
        @Override
        public void onTabUnselected(ActionBar.Tab tab,
                FragmentTransaction fragmentTransaction) {
        }
    
        @Override
        public void onTabReselected(ActionBar.Tab tab,
                FragmentTransaction fragmentTransaction) {
        }
    
        /**
         * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
         * one of the sections/tabs/pages.
         */
        public class SectionsPagerAdapter extends FragmentPagerAdapter {
    
            public SectionsPagerAdapter(FragmentManager fm) {
                super(fm);
            }
    
            @Override
            public Fragment getItem(int position) {
                // getItem is called to instantiate the fragment for the given page.
                // Return a DummySectionFragment (defined as a static inner class
                // below) with the page number as its lone argument.
                Fragment fragment = new DummySectionFragment();
                Bundle args = new Bundle();
                args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
                fragment.setArguments(args);
                return fragment;
            }
    
            @Override
            public int getCount() {
                // Show 3 total pages.
                return 3;
            }
    
            @Override
            public CharSequence getPageTitle(int position) {
                Locale l = Locale.getDefault();
                switch (position) {
                case 0:
                    return getString(R.string.title_menu_truck1).toUpperCase(l);
                case 1:
                    return getString(R.string.title_menu_truck2).toUpperCase(l);
                case 2:
                    return getString(R.string.title_menu_truck3).toUpperCase(l);
                }
                return null;
            }
        }
    
        /**
         * A dummy fragment representing a section of the app, but that simply
         * displays dummy text.
         */
        public static class DummySectionFragment extends Fragment {
            /**
             * The fragment argument representing the section number for this
             * fragment.
             */
            public static final String ARG_SECTION_NUMBER = "section_number";
    
            public DummySectionFragment() {
            }
    
            @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container,
                    Bundle savedInstanceState) {
                View rootView = inflater.inflate(R.layout.fragment_truck_dummy,
                        container, false);
    //          TextView dummyTextView = (TextView) rootView
    //                  .findViewById(R.id.section_label);
    //          dummyTextView.setText(Integer.toString(getArguments().getInt(
    //                  ARG_SECTION_NUMBER)));
                int pos=getArguments().getInt(ARG_SECTION_NUMBER);
                if(pos==1){
    //              dummyTextView.setText("Selected Truck");
                }else if(pos==2){
    //              dummyTextView.setText("Selected Tripsheet");
                }else if(pos==3){
    //              dummyTextView.setText("Selected Alerts");
                }
                return rootView;
            }
        }
    
    }
    

    fragment_truck_dummy.xml

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:background="#000"
        tools:context=".TruckActivity$DummySectionFragment" >
    
        <!-- <TextView
            android:id="@+id/section_label"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#FFF" /> -->
       <fragment
            android:id="@+id/sub_frag"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            class="com.freight.fragments.TruckStatus"       />   
    
    </RelativeLayout>
    

    TruckStatus.java

    package com.freight.fragments;
    
    import com.clacion.freightexchange.R;
    
    import android.app.Fragment;
    import android.os.Bundle;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    
    public class TruckStatus extends Fragment {
    
        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onActivityCreated(savedInstanceState);
        }
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            View v =inflater.inflate(R.layout.truck_status_fragment,
                    container, false);
            return v;
        }
    
    }
    

    My LogCat

    07-04 12:17:33.534: E/AndroidRuntime(795): FATAL EXCEPTION: main
    07-04 12:17:33.534: E/AndroidRuntime(795): android.view.InflateException: Binary XML file line #17: Error inflating class fragment
    07-04 12:17:33.534: E/AndroidRuntime(795):  at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
    07-04 12:17:33.534: E/AndroidRuntime(795):  at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
    07-04 12:17:33.534: E/AndroidRuntime(795):  at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
    07-04 12:17:33.534: E/AndroidRuntime(795):  at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
    07-04 12:17:33.534: E/AndroidRuntime(795):  at com.freight.activities.TruckActivity$DummySectionFragment.onCreateView(TruckActivity.java:177)
    07-04 12:17:33.534: E/AndroidRuntime(795):  at android.support.v4.app.Fragment.performCreateView(Fragment.java:1460)
    07-04 12:17:33.534: E/AndroidRuntime(795):  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:911)
    07-04 12:17:33.534: E/AndroidRuntime(795):  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1088)
    07-04 12:17:33.534: E/AndroidRuntime(795):  at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
    07-04 12:17:33.534: E/AndroidRuntime(795):  at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1444)
    07-04 12:17:33.534: E/AndroidRuntime(795):  at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:461)
    07-04 12:17:33.534: E/AndroidRuntime(795):  at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
    07-04 12:17:33.534: E/AndroidRuntime(795):  at android.support.v4.view.ViewPager.populate(ViewPager.java:1064)
    07-04 12:17:33.534: E/AndroidRuntime(795):  at android.support.v4.view.ViewPager.populate(ViewPager.java:911)
    07-04 12:17:33.534: E/AndroidRuntime(795):  at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1432)
    07-04 12:17:33.534: E/AndroidRuntime(795):  at android.view.View.measure(View.java:15518)
    07-04 12:17:33.534: E/AndroidRuntime(795):  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4825)
    07-04 12:17:33.534: E/AndroidRuntime(795):  at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
    07-04 12:17:33.534: E/AndroidRuntime(795):  at android.view.View.measure(View.java:15518)
    07-04 12:17:33.534: E/AndroidRuntime(795):  at android.widget.LinearLayout.measureVertical(LinearLayout.java:847)
    07-04 12:17:33.534: E/AndroidRuntime(795):  at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
    07-04 12:17:33.534: E/AndroidRuntime(795):  at android.view.View.measure(View.java:15518)
    07-04 12:17:33.534: E/AndroidRuntime(795):  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4825)
    07-04 12:17:33.534: E/AndroidRuntime(795):  at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
    07-04 12:17:33.534: E/AndroidRuntime(795):  at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2176)
    07-04 12:17:33.534: E/AndroidRuntime(795):  at android.view.View.measure(View.java:15518)
    07-04 12:17:33.534: E/AndroidRuntime(795):  at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1874)
    07-04 12:17:33.534: E/AndroidRuntime(795):  at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1089)
    07-04 12:17:33.534: E/AndroidRuntime(795):  at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1265)
    07-04 12:17:33.534: E/AndroidRuntime(795):  at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:989)
    07-04 12:17:33.534: E/AndroidRuntime(795):  at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4351)
    07-04 12:17:33.534: E/AndroidRuntime(795):  at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
    07-04 12:17:33.534: E/AndroidRuntime(795):  at android.view.Choreographer.doCallbacks(Choreographer.java:562)
    07-04 12:17:33.534: E/AndroidRuntime(795):  at android.view.Choreographer.doFrame(Choreographer.java:532)
    07-04 12:17:33.534: E/AndroidRuntime(795):  at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
    07-04 12:17:33.534: E/AndroidRuntime(795):  at android.os.Handler.handleCallback(Handler.java:725)
    07-04 12:17:33.534: E/AndroidRuntime(795):  at android.os.Handler.dispatchMessage(Handler.java:92)
    07-04 12:17:33.534: E/AndroidRuntime(795):  at android.os.Looper.loop(Looper.java:137)
    07-04 12:17:33.534: E/AndroidRuntime(795):  at android.app.ActivityThread.main(ActivityThread.java:5041)
    07-04 12:17:33.534: E/AndroidRuntime(795):  at java.lang.reflect.Method.invokeNative(Native Method)
    07-04 12:17:33.534: E/AndroidRuntime(795):  at java.lang.reflect.Method.invoke(Method.java:511)
    07-04 12:17:33.534: E/AndroidRuntime(795):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
    07-04 12:17:33.534: E/AndroidRuntime(795):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
    07-04 12:17:33.534: E/AndroidRuntime(795):  at dalvik.system.NativeStart.main(Native Method)
    07-04 12:17:33.534: E/AndroidRuntime(795): Caused by: java.lang.ClassCastException: com.freight.fragments.TruckStatus cannot be cast to android.support.v4.app.Fragment
    07-04 12:17:33.534: E/AndroidRuntime(795):  at android.support.v4.app.Fragment.instantiate(Fragment.java:394)
    07-04 12:17:33.534: E/AndroidRuntime(795):  at android.support.v4.app.Fragment.instantiate(Fragment.java:369)
    07-04 12:17:33.534: E/AndroidRuntime(795):  at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:272)
    07-04 12:17:33.534: E/AndroidRuntime(795):  at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:676)
    07-04 12:17:33.534: E/AndroidRuntime(795):  ... 43 more
    

    Am using Android 4.2.2 APIs 17..Does anybody have any idea about it?