Question

I'm compiling an Android project against API Level 11 (3.0) and I have this code:

if (parent instanceof AbsListView) {
    checked = ((AbsListView)parent).isItemChecked(position);
}

When I run this in pre-3.0 (lower than API Level 11) devices, I get this error:

java.lang.NoSuchMethodError: android.widget.AbsListView.isItemChecked

In AbsListView documentation, isItemChecked is stated as having API Level 1 compatibility, then why do I get the error?

Was it helpful?

Solution

Apparently this is what happens:

Since API Level 1, Android framework has already isItemChecked on ListView.

However, on the release of API Level 11, Google moved the definition of isItemChecked to AbsListView, which is the superclass of ListView. This change doesn't prevent existing code (meant for compiling against pre-API Level 11) to compile against API Level 11, but the generated .class file actually looks for isItemChecked on AbsListView, which does not exist on pre-API Level 11 devices.

On the API Differences Report, it is stated:

boolean isItemChecked(int) Method was locally defined, but is now inherited from AbsListView.

This is a dangerous pitfall, because the compatibility can't be checked on compile-time at all. You must remember to cast it as ListView and not AbsListView. Maybe we should avoid AbsListView altogther.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top