ClassCastException on a subclass of ListFragment using compatibility library
Asked Answered
B

2

15

This only happens when using the compatibility library for pre-3.0 devices

I'm getting an error that I cannot pin down. I have an Activity with a ListFragment and standard Fragment. It is just like the example provided in the Developers section of the Android Dev Guide.

ListFragment Subclass (no functions overridden)

public class ItemListFragment extends ListFragment

MainActivity

public class ItemViewerActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.item_viewer);
    }
}

Xml Layout for MainActivity

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:orientation="horizontal">
  <fragment class="org.example.ItemListFragment"
    android:id="@+id/item_list_fragment"
    android:layout_width="0dp"
    android:layout_height="fill_parent"
    android:layout_weight="1" />
  <FrameLayout
    android:id="@+id/item_info_frame"
    android:layout_width="0dp"
    android:layout_height="fill_parent"
    android:layout_weight="1" />
</LinearLayout>

Error Message from LogCat

ERROR/AndroidRuntime: Caused by: java.lang.ClassCastException: org.example.ItemListFragment cannot be cast to android.app.Fragment

Busby answered 3/5, 2011 at 19:18 Comment(0)
B
35

After some serious googling, I found an article that pointed out a nice little tidbit. When using the compatibility library, your activities that use fragments have to extend FragmentActivity. Once I did that, the error did not present itself again.

Busby answered 3/5, 2011 at 19:29 Comment(3)
I also got this error when I was correctly using FragmentActivity but forgot to use getSupportFragmentManager() instead of getFragmentManager().Participate
Also if the super.onCreate(savedInstanceState); is missing on the Activity the same error will rise and not the usual SuperNotCalledExceptionMulvaney
I was wondering how would I extend ActionBarActivity and FragmentActivity both at the same time, but then I found that extending ActionBar activity takes care of it!Rheum
A
1

For me the problem was that I had forgotten to change the manifest. Following the suggestion of the tutorial I converted my Activity to a Fragment and made a shell Activity to call it. My manifest still pointed to the Fragment class leading to a Class Cast Exception.

Anting answered 5/10, 2011 at 19:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.