androidandroid-fragmentsandroid-1.6-donutandroid-support-library

ClassCastException on a subclass of ListFragment using compatibility library


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


Solution

  • 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.