Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to solve java.lang.NoSuchMethodError: android.widget.AbsListView.isItemChecked

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?

like image 990
Randy Sugianto 'Yuku' Avatar asked Sep 05 '11 09:09

Randy Sugianto 'Yuku'


1 Answers

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.

like image 145
Randy Sugianto 'Yuku' Avatar answered Oct 01 '22 16:10

Randy Sugianto 'Yuku'