Android Studio: ClassNotFoundException

2019-02-21 14:14发布

问题:

i was busy with my app for over a week, when suddenly:

11-12 07:59:17.860    1653-1653/nl.test.myapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{nl.test.MyApp/nl.test.MyApp.MainActivity}: java.lang.ClassNotFoundException: Didn't find class "nl.test.myapp.MainActivity" on path: DexPathList[[zip file "/data/app/nl.test.myapp-2.apk"],nativeLibraryDirectories=[/data/app-lib/nl.test.myapp-2, /system/lib]]
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2137)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
        at android.app.ActivityThread.access$600(ActivityThread.java:141)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:5103)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:525)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
        at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.ClassNotFoundException: Didn't find class "nl.test.myapp.MainActivity" on path: DexPathList[[zip file "/data/app/nl.test.MyApp-2.apk"],nativeLibraryDirectories=[/data/app-lib/nl.test.MyApp-2, /system/lib]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:53)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
        at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2128)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
        at android.app.ActivityThread.access$600(ActivityThread.java:141)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:5103)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:525)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
        at dalvik.system.NativeStart.main(Native Method)

here is my AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="nl.test.myapp"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="7"
        android:targetSdkVersion="19" />

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="nl.test.myapp.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".welcomewizard.WelcomeWizardIntroPage"
            android:label="@string/app_name" />

        <activity android:name=".welcomewizard.WelcomeWizardPage1"
            android:label="@string/app_name" />

        <activity android:name=".welcomewizard.WelcomeWizardPage2"
            android:label="@string/app_name" />

        <activity android:name=".welcomewizard.WelcomeWizardPage3"
            android:label="@string/app_name" />

        <activity android:name=".welcomewizard.WelcomeWizardPage4"
            android:label="@string/app_name" />

        <activity android:name=".welcomewizard.WelcomeWizardFinishPage"
            android:label="@string/app_name" />

        <activity android:name=".CompanySelectorActivity"
            android:label="@string/compsel_actionbarlabel" />
    </application>

</manifest>

this was happening after some problems with my R.java (the id's for the views where incorrect), after rebuilding the project this problem happend

i've already tried the Invalidate Cashes/restart in the IDE File-menu

Update 14:51: this is my compiler.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="CompilerConfiguration">
    <option name="DEFAULT_COMPILER" value="Javac" />
    <resourceExtensions />
    <wildcardResourcePatterns>
      <entry name="!?*.java" />
      <entry name="!?*.form" />
      <entry name="!?*.class" />
      <entry name="!?*.groovy" />
      <entry name="!?*.scala" />
      <entry name="!?*.flex" />
      <entry name="!?*.kt" />
      <entry name="!?*.clj" />
    </wildcardResourcePatterns>
    <annotationProcessing>
      <profile default="true" name="Default" enabled="false">
        <processorPath useClasspath="true" />
      </profile>
    </annotationProcessing>
  </component>
</project>

My MainActivity.java file (\src\main\java\nl\test\myapp\MainActivity.java) :

package nl.test.myapp;

import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.widget.RelativeLayout;

import nl.test.myapp.welcomewizard.WelcomeWizardIntroPage;

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        setBackground(R.drawable.background_grey);

        Intent intent = new Intent(this, WelcomeWizardIntroPage.class);
        startActivity(intent);
        finish();
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void setBackground(int drawable){
        int currentApiVersion = android.os.Build.VERSION.SDK_INT;
        if(currentApiVersion >= android.os.Build.VERSION_CODES.JELLY_BEAN){
            RelativeLayout layout = (RelativeLayout) findViewById(R.id.layout_main);
            layout.setBackground(getResources().getDrawable(drawable));
        }
    }
}

回答1:

Close android studio. Navigate to the project folder. Delete all files relating to intelliJ (Android Studio) i.e

  • .idea (folder)
  • *.imi (files)

Also make sure that package name matches the package in the android manifest.xml.

Then reimport the project.

This happened to me because I renamed the root package and IntelliJ (android studio) didn't track this.



回答2:

I created a new project in Android studio and copied everything from the old project into the new one. Now it's working again, without any(!) modifications to the code.



回答3:

I had the same problem, turns out I screwed up with some final method. Be sure to check dalvikvm errors in logcat output before the FATAL EXCEPTION. I will give you some hints on the problem. In my case, I had a final method (isResumed) which was already defined in the base class - causing runtime crash. Wasn't complaining at compile time.

Check the logs:

E/dalvikvm( 9984): Method Lcom/your/package/ui/SomeActivity;.isResumed overrides final Landroid/app/Activity;.isResumed
W/dalvikvm( 9984): failed creating vtable
...
D/AndroidRuntime( 9962): Shutting down VM
...
E/AndroidRuntime(10065): FATAL EXCEPTION: main
E/AndroidRuntime(10065): Process: com.yourpackage.ui, PID: 10065
E/AndroidRuntime(10065): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.yourpackage.ui/com.yourpackage.ui.HomeActivity}: java.lang.ClassNotFoundException: Didn't find class "com.yourpackage.ui.HomeActivity" on path: DexPathList[[zip file "/data/app/com.yourpackage.ui-2.apk"],nativeLibraryDirectories=[/data/app-lib/com.yourpackage.ui-2, /vendor/lib, /system/lib]]
...


回答4:

I ran into this. My app had been running fine and one day it just started running into these ClassNotFoundExceptions. My code hadn't changed at all.

As far as I can tell, it ended up being a bug in the build of Android Studio. I had recently updated to the latest release on the canary channel.

Switching back to an older release on the dev channel got things working again:

  1. Go into Settings / Appearance & Behavior / System Settings / Update
  2. Change to Dev Channel and Check Now.


回答5:

I had the similar problem. I remembered, that previously "not enough memory" message was shown and the application uploading process could not finish, stopping on dexDebug with error. Then I released enough memory, but application started with ClassNotFoundException.
The solution that worked for me was to delete all "build" folders in the project. I suppose that gradle can put corrupted files to "build" folder when there is not enough memory.



回答6:

You can check Multidex mechanism. The reason may be method numbers overflow.

  1. Add MultiDex.install(this); to your Application:

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

    afterEvaluate {
       tasks.matching {
           it.name.startsWith('dex')
       }.each { dx ->
           if (dx.additionalParameters == null) {
               dx.additionalParameters = []
           }
           dx.additionalParameters += '--multi-dex' // enable multidex
       }
    }
    

to your app module's gradle.build



回答7:

   try: 
   <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>


回答8:

Looks like you have a namespace typo somewhere. Search for MyApp and change it to myapp.



回答9:

Your MainActivity.java is excluded from compile, so this class isn't included in .apk. Remove line:

<file url="file://$PROJECT_DIR$/src/nl/test/MyApp.java" />

from the excludeFromCompile section of the .idea/compiler.xml file (or you can do this from IDE settings).

Source



回答10:

i don't know this will help you..anyway try to use application theme as @style/Theme.AppCompat..we must use as per developers forum.

<application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/Theme.AppCompat" >

       <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>


回答11:

As i can see in your Log ,

nativeLibraryDirectories=[/data/app-lib/nl.test.myapp-2, /system/lib

For that you can change your lib to libs , I did this and it resolved my problem.

you would see some error mark on project to resolve that go to project properties and java build path, Remove all the libraries from there . You will not see this error again. :)



回答12:

When using Android Studio, please ensure that the "src" folder that contains your Java class is marked as "Source Root". Otherwise, it will not make it into the APK.



回答13:

In my case it was manifest declaration of android.app.Application in project and actual code in module.



回答14:

This happened to me too, and none of the postings here helped. My problem was also caused by my having renamed the root package. My ClassNotFoundException was showing a DexPathList which was the old path to my package. I found the cause was in my Gradle Script called "build.gradle (Module: app)" I had a line saying: applicationId "old package name". I changed this to the new package name, did a gradle sync, and everything worked.



回答15:

If you're creating an android library, you may simply have forgotten to import your library in your app build.gradle with the implementation project keyword :

dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) testImplementation 'junit:junit:4.12' implementation 'com.android.support:design:27.0.2' implementation 'com.android.support:mediarouter-v7:27.0.2' implementation project(':mylib-module:mymodule') implementation 'com.google.firebase:firebase-core:10.0.1' }

Hope this helps :)



回答16:

GO to Build Menu and Clean Project.

The above solution worked perfectly fine for me.