Android 5.x ClassNotFoundException works fine on 6.0+
Asked Answered
Y

11

31

I have updated my project's minSdkVersion from 19 to 21. This has caused an issue on 5.0/5.1 devices where I can't run the app. I keep getting a ClassNotFoundException on my Application class. The full log, Application class, and gradle file are below. If I revert my project back to minSdkVersion 19 then the app will run on 4.4+ with no problems.

What I have tried

  • Cleaning/Rebuilding

  • Updating and downgrading the build tools version

  • All support library's across projects have same version number

  • Making all my manifest classes relative and then absolute

  • Updated all Sdk and build tools

Log

04-27 14:37:07.152 6278-6278/? E/AndroidRuntime: FATAL EXCEPTION: main
     Process: com.package.testapp, PID: 6278
     java.lang.RuntimeException: Unable to instantiate application com.package.TestApplication: java.lang.ClassNotFoundException: Didn't find class "com.package.Application" on path: DexPathList[[zip file "/data/app/com.package.testapp-1/base.apk"],nativeLibraryDirectories=[/data/app/com.package.testapp-1/lib/x86_64, /vendor/lib64, /system/lib64]]
         at android.app.LoadedApk.makeApplication(LoadedApk.java:563)
         at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4526)
         at android.app.ActivityThread.access$1500(ActivityThread.java:151)
         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)
         at android.os.Handler.dispatchMessage(Handler.java:102)
         at android.os.Looper.loop(Looper.java:135)
         at android.app.ActivityThread.main(ActivityThread.java:5254)
         at java.lang.reflect.Method.invoke(Native Method)
         at java.lang.reflect.Method.invoke(Method.java:372)
         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
      Caused by: java.lang.ClassNotFoundException: Didn't find class "com.package.TestApplication" on path: DexPathList[[zip file "/data/app/com.package.testapp-1/base.apk"],nativeLibraryDirectories=[/data/app/com.package.testapp-1/lib/x86_64, /vendor/lib64, /system/lib64]]
         at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
         at android.app.Instrumentation.newApplication(Instrumentation.java:980)
         at android.app.LoadedApk.makeApplication(LoadedApk.java:558)
         at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4526) 
         at android.app.ActivityThread.access$1500(ActivityThread.java:151) 
         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364) 
         at android.os.Handler.dispatchMessage(Handler.java:102) 
         at android.os.Looper.loop(Looper.java:135) 
         at android.app.ActivityThread.main(ActivityThread.java:5254) 
         at java.lang.reflect.Method.invoke(Native Method) 
         at java.lang.reflect.Method.invoke(Method.java:372) 
         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
        Suppressed: java.lang.ClassNotFoundException: com.package.testapp.welcome.TestClaimApplication
         at java.lang.Class.classForName(Native Method)
         at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
         at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
                ... 13 more
      Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available

Gradle

    buildscript {
    repositories {
        maven { url 'https://maven.fabric.io/public' }
    }

    dependencies {
        classpath 'io.fabric.tools:gradle:1.+'
    }
    }

    apply plugin: 'com.android.application'
    apply plugin: 'io.fabric'

    repositories {
    maven { url 'https://maven.fabric.io/public' }
    }

android {

    compileSdkVersion 25
    buildToolsVersion '25.0.3'

    defaultConfig {
        applicationId "com.package.testapp"
        minSdkVersion 21
        multiDexEnabled = true
        targetSdkVersion 25
        versionCode 2
        versionName "0.7"
        renderscriptTargetApi 18 // support mode not supported 21+
        renderscriptSupportModeEnabled true
        testInstrumentationRunner 
    "android.support.test.runner.AndroidJUnitRunner"
    }
    dexOptions {
        javaMaxHeapSize "4g"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    lintOptions {
        checkReleaseBuilds false
        abortOnError false
    }

    productFlavors {
        companylocal
        companymaven
    }
}

dependencies {


    def ext = rootProject.ext;

    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile "com.android.support:appcompat-v7:${ext.supportLibraryVersion}"
    compile "com.android.support:design:${ext.supportLibraryVersion}"
    compile 'com.romandanylyk:pageindicatorview:0.0.9'
    compile "com.jakewharton:butterknife:${ext.butterknifeLibraryVersion}"
    annotationProcessor "com.jakewharton:butterknife-compiler:${ext.butterknifeLibraryVersion}"
    compile "uk.co.chrisjenx:calligraphy:2.2.0"
    compile 'com.android.support:multidex:1.0.1'
    // Crashlytics Kit - for crash handling
    compile('com.crashlytics.sdk.android:crashlytics:2.5.2@aar') {
        transitive = true
    }
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    testCompile 'junit:junit:4.12'
    testCompile 'org.robolectric:robolectric:3.0'
    testCompile "com.squareup.okhttp3:mockwebserver:${ext.okHttp3LibraryVersion}"
    testCompile('com.squareup.assertj:assertj-android:1.1.1') {
        exclude module: 'support-annotations'
    }
}

Application

public class TestApplication extends Application {

    Engine engine;

    @Override
    public void onCreate() {
        super.onCreate();

        String privateServerUrlLocal = getString(R.string.server_url);
        ProfileLauncher profileLauncher = getProfileLauncher();
        LoginLauncher loginLauncher = getLoginLauncher();

        // Set up Crash Analytics
        final CrashlyticsCore crashlyticsCore = new CrashlyticsCore.Builder().disabled(DEBUG).build();
        Fabric.with(this, new Crashlytics.Builder().core(crashlyticsCore).build());

        Intent intent = new Intent(this, LogoutService.class);
        startService(intent);

        CertificatePinner certificatePinner = new CertificatePinner.Builder()
                .add("")
                .add("")
                .build();

        engine = new Engine.Builder(privateServerUrlLocal, getString(R.string.other_server_url))
                .setCertificatePinner(certificatePinner)
                .setSDKPartnerSetupManager(getSdkPartnerManager())
                .setLogoutActionHandler(getLogoutActionHandler())
                .setVLocationManager(new VLocationManagerImp())
                .setDebug(DEBUG)
                .addDeepLinkHandler(new ClaimDeepLinkHandler(loginLauncher, profileLauncher))
                .addDeepLinkHandler(new LinkGiftCodeDeeplinkHandler(loginLauncher, profileLauncher))
                .addDeepLinkHandler(new OpenLinkDeepLinkHandler())
                .addDeepLinkHandler(new DetailsDeepLinkHandler())
                .addClaimConfig(new ClaimConfig(false, false, false, false, true))
                .build();
        engine.startup(this);
    }



    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(base);
    }

}

Manifest

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.package.testapp">

<uses-feature
    android:name="android.hardware.camera"
    android:required="true" />
<uses-feature
    android:name="android.hardware.camera.autofocus"
    android:required="false" />
<uses-feature
    android:name="android.hardware.camera.flash"
    android:required="false" />

<!-- Required for g+ login -->
<uses-permission android:name="android.permission.CAMERA" />

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <application
        android:name=".TestApplication"
        android:allowBackup="false"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <service
            android:name="com.package.companycommon.ui.LogoutService"
            android:stopWithTask="true" />

        <activity
            android:name=".LaunchActivity"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity
            android:name=".welcome.WelcomeActivity"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme.NoActionBar.ClearStatus" />
        <activity
            android:name=".RegisterActivity"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme.NoActionBar.ClearStatus"
            android:windowSoftInputMode="adjustResize" />
        <activity
            android:name=".LoginActivity"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme.NoActionBar.ClearStatus"
            android:windowSoftInputMode="adjustResize" />
        <activity
            android:name=".ActivationActivity"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme.NoActionBar.ClearStatus"
            android:windowSoftInputMode="adjustResize" />
        <activity
            android:name=".AddPhoneNumberActivity"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme.NoActionBar.ClearStatus"
            android:windowSoftInputMode="adjustResize" />
        <activity
            android:name=".ForgotPasswordActivity"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme.NoActionBar.ClearStatus"
            android:windowSoftInputMode="adjustResize" />
        <activity
            android:name=".GiftHistoryActivity"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme.NoActionBar.ClearStatus" />
        <activity
            android:name="com.package.PartnerLoginHiddenActivity"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme.NoActionBar.ClearStatus" />
        <activity
            android:name=".tutorial.TutorialActivity"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme.NoActionBar.ClearStatus" />
        <activity
            android:name=".CreateNewPasswordActivity"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme.NoActionBar.ClearStatus" />
        <activity
            android:name=".settings.SettingsActivity"
            android:screenOrientation="portrait">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".GiftHistoryActivity" />
        </activity>
        <activity
            android:name=".settings.ExtraSettingsActivity"
            android:label="@string/settings"
            android:screenOrientation="portrait">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".settings.SettingsActivity" />
        </activity>
        <activity
            android:name="companyapp.company.NewsActivity"
            android:label="@string/notifications"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme" />
        <activity
            android:name=".termsandconditions.CompanyTermsAndConditionsActivity"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme" />

        <activity
            android:name="com.package.companycommon.ui.PhotoViewerActivity"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme" />

        <activity
            android:name="com.package.company.details.CompanyDetailActivity"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme" />
        <activity
            android:name="com.package.company.details.CompanyDetailActivityLocation"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.package.company.details.CompanyDetailActivity" />
        </activity>
        <activity
            android:name="com.package.company.ClaimActivity"
            android:theme="@style/AppTheme.NoActionBar"
            tools:replace="android:theme" />
    </application>

</manifest>
Yorker answered 27/4, 2017 at 19:29 Comment(19)
Can you share you AndroidManifest.xml ?Harrie
added the manifestYorker
Did you uninstall the app before installing it? Also init MultiDex in onCreate()Isotone
Yeah, uninstalled and cleaned every time before installing the app. Multidex is installed in attachBaseContextYorker
Restart your phone, invalidate cache and restart in your android studioIsotone
I have tried all of that, including a different android studio, different phone and different computerYorker
Have you tried disabling instant run?Traveller
Inside your application tag ,give full path of class rather than just dotted part (.TestApplication)Covert
Remove the = symbol while assigning true to multiDexEnabled within DefaultConfig in Gradle. After that give a try.Pavid
can you show me your compiler.xml file from .idea directory inside project-level.Quadruped
had same error, i deleted my .idea, .gradle, app-level build, project-level build directories and extended application class with MultiDexApplication. give it a try.Quadruped
Unrelated: Support RenderScript is not needed on API 21. Platform RenderScript supports everything on API 21. Save a few MB off your APK and remove support RenderScript. Intrinsic blur is supported since API 18 so you probably never needed support RenderScript.Ambassadress
thanks for the tip. Will Renderscript supportYorker
Did you find any solution?Kelle
I have the exact same problem. Please post here if you have found a solution.Hays
I found a solution. It happened to be because I had all of the play-services in my gradle file instead of just the one's I needed. I don't know why this caused issues in 5.0, but one I only added the play-services I needed and it worked fineYorker
@Yorker can you please post your exact solution.Wagoner
@Yorker can you please how you solved it same problem for me as wellRawlins
Answer posted aboveYorker
Y
9

When targeting api 21 the compiler has a limit of 100 dex files it will read. So a simple solution I found was to add this to your dexOptions in your gradle file. This will merge all your dex files into the lowest possible amount.

In your build.gradle file add the following

android {
    ...
    dexOptions {
        preDexLibraries = false
    }
}
Yorker answered 19/12, 2017 at 15:45 Comment(1)
Indeed, there is a limit of 100 dex files. android.googlesource.com/platform/art/+/lollipop-release/…Sarah
C
5

Please try to disable the Instant Run option and then run the app . It worked for me after trying lot of solutions I finally solved this.

enter image description here

Counterscarp answered 30/7, 2017 at 9:49 Comment(2)
This also worked for me. I was sent on a wild goose chase of multi-dex keep files.Consummate
This did not work for me. It did change the missing class to a different class, but it still failed on startup.Epistyle
C
2

Try removing compile 'com.android.support:multidex:1.0.1'. The Google doc says

Therefore, if your minSdkVersion is 21 or higher, you do not need the multidex support library.

I am by no means sure if this helps, but it may be worth trying.

Canon answered 30/4, 2017 at 13:14 Comment(0)
C
1

This means your multiDex does not work properly so some files are missing. I think android 5.0 has the different way to use the multiDex. Did you override something in your Aplication class?

Coltun answered 27/4, 2017 at 20:20 Comment(4)
The only method's I override are onCreate and attachBaseContext. You can see my implementation of them in the code aboveYorker
I think you need to remove attachBaseContext(). it is used for android 4.0. in 5.0 you do not need it. Can you try to remove it?Coltun
Try clean and rebuild and let us know.Trillion
I removed attachBaseContext() then cleaned, rebuilt and uninstalled and same thing happened.Yorker
S
1

For some reason, this class is not in your main dex anymore.

Declare the class in the main-classes list, using multiDexKeepFile (listing the classes in gradle) or multiDexKeepProguard (pointing to a specific proguard file for the main classes).

Sarah answered 2/5, 2017 at 13:21 Comment(0)
L
1

Try enabling Progaud and disabling multidex.

You'll not only fix this problem, but you'll have a smaller apk with faster install and run times.

Note, If you need help with this just leave a comment and we can work it out.

  • Ok, so its not Progaurd or MultiDex

The error is that com.package.Application is missing. None of the code you posted (or the manifest) contains a reference to that class. Where are you defining com.package.Application? and if you aren't where in your project is it being referenced? (I'd do a project wide search for "com.package.Application" to unravel this.)

Liability answered 2/5, 2017 at 14:11 Comment(4)
Yeah, i disabled multidex and enabled proguard. Still getting the same errorYorker
Updated answer. please take a lookLiability
sorry, i just changed the name of the application in the question and forgot to change it in the log. The name of the application is TestApplication like the manifest and the classYorker
Note: in the log one can see that the class which is missing is com.package.testapp.welcome.TestClaimApplicationClamper
H
1

try giving full path in manifest-

  <application
        android:name=".TestApplication"

Also delete the build folder manually-sometimes clean doesn't work.Also uninstall the app manually and start.

Harmonist answered 4/5, 2017 at 19:4 Comment(1)
I tried using all relative and absolute paths in the manifest. Also tried just relative/absolute paths for the Application class. Also tried deleting the build folder. I always uninstall the app since this problem has come up.Yorker
S
1

I have made demo from your code and configuration and its working in below marshmallow

Download and check it and compare with your code. And one more thing how you have created project with package name com.package.testapp. I am not able to create project with same package name

Scribble answered 6/5, 2017 at 5:49 Comment(0)
R
1

Create multidex-config.txt to keep this classes in the primary DEX file:

com/package/Application.class
com/package/TestApplication.class
com/package/testapp/welcome/TestClaimApplication.class

Add multiDexKeepFile to android.buildTypes.release section of your build.gradle like this:

android {
    buildTypes {
        release {
            multiDexKeepFile file 'multidex-config.txt'
        }
    }
}
Russ answered 6/5, 2017 at 12:8 Comment(0)
P
-1

Do you need multidex enabled? I have always run into issues with it. I always understood multidex to be used as a last resort if you are still hitting the 65k method limit. If you are not running into this method limit, you do not need multidex. If you are running into this limit, I would suggest using progaurd to remedy the issue first. If you are still above the method limit even after using proguard, then use multidex.

Priapic answered 28/4, 2017 at 3:1 Comment(1)
I do need multidex enabledYorker
T
-1

You need to add your android:name with complete path like this.

android:name="android.support.multidex.MultiDexApplication" 

And your TestApplication should extend MultiDexApplication.

According to the documentation, please refer if need more details. MultiDex Documentation

Tartrazine answered 4/5, 2017 at 13:1 Comment(1)
I have tried that. Answer below suggested the same thing https://mcmap.net/q/465439/-android-5-x-classnotfoundexception-works-fine-on-6-0Yorker

© 2022 - 2024 — McMap. All rights reserved.