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

Programmer Bruce
  • 64,977
  • 7
  • 99
  • 97
Spidy
  • 39,723
  • 15
  • 65
  • 83

2 Answers2

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.

Spidy
  • 39,723
  • 15
  • 65
  • 83
  • 8
    I also got this error when I was correctly using `FragmentActivity` but forgot to use `getSupportFragmentManager()` instead of `getFragmentManager()`. – LouieGeetoo Sep 17 '11 at 19:39
  • 1
    Also if the `super.onCreate(savedInstanceState);` is missing on the Activity the same error will rise and not the usual `SuperNotCalledException` – Augusto Hack Nov 10 '12 at 02:03
  • 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! – Vivek Todi Dec 29 '13 at 10:42
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.