Search code examples
javaandroidandroid-gradle-pluginnoclassdeffounderror

Fatal Exception: java.lang.NoClassDefFoundError when calling static method in Android app


One of our beta testers using a T-mobile Galaxy S4 running Android 4.4.4 is experiencing very strange NoClassDefFoundError crashes. I'm completely at a loss for why these could be happening.

The most recent one happens when a static method is called in onCreateView in a fragment.

MyCustomClass.getNumberOfItems(getActivity());

fails with

Fatal Exception: java.lang.NoClassDefFoundError com.mycompany.myapp.utilities.MyCustomClass$5

Here's the method in question:

public static List<Item> getNumberOfItems(final Context context)
{
    List<Item> allFinishedItems = getAllFinishedItems(context);

    CollectionUtils.filter(allFinishedItems, new Predicate<Item>()
    {
        @Override
        public boolean evaluate(Item item)
        {
            // TODO Auto-generated method stub
            return isNonCustomItem(context, item);
        }
    });

    return allFinishedItems;
}

1.) what is the "$5" after the class name? (answer: reference to anonymous class for filtering with CollectionUtils.filter) 2.) this user had another crash of similar nature, but with a completely different static method call that's in a library that's included via gradle. The crash I'm referencing in this question is coming from code that is part of my own library project, and the same static method call works in other places in the app. This problem seems to be spreading, or at least not contained to 1 class or 1 library.

We're targeting the following Android versions in build.gradle:

minSdkVersion 14
targetSdkVersion 22  (android 5.1)

What could possibly be going on here? One other thing to note is that the signed APKs were generated using Android Studio 2.0 preview 4. However, the app works fine for 20-30 other beta testers, so I'm hesitant to point the finger at using a preview version of Studio.


Solution

  • The NoClassDefFoundErrors were happening because multidex was only partially implemented in this app - for some reason, this works fine on Android 5/6 but on Android 4.x it makes your app crash with NoClassDefFoundError in random places. It seems to me like this situation should be detected by Android Studio and you should be warned you've improperly implemented multidex support.

    To fix it, make sure the following is true for your project:

    1. multiDexEnabled = true in the defaultConfig section of your app-level build.gradle

    2. compile 'com.android.support:multidex:1.0.0' in your project-level build.gradle

    3. Call MultiDex.install() in attachBaseContext() of your Application class.

    More details on multidex can be found here.