Android: Unable to instantiate activity / ClassNotFoundException
Asked Answered
W

32

70

I recently published an app to the market and I'm now getting an error by some user, the app presumably crashes right when it starts. Unfortunately I can't contact him directly and the app works fine in the emulator as well as on my phone (and some friends' phones).
EDIT: I guess that this happens to more than one user as I received comments in the market like "crashes on start" or "doesn't work". I only received this one stacktrace but there's no info about the configuration, device, Android version, etc.

The app is a simple soundboard, so there's really no magic involved, but I can't get why it fails on some phones. Here's the stack trace I'm getting, I hope anybody can help me out:

java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.my.app/com.my.app.SoundMachine}: java.lang.ClassNotFoundException: com.my.app.SoundMachine in loader dalvik.system.PathClassLoader[/mnt/asec/com.my.app-1/pkg.apk]
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2585)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
at android.app.ActivityThread.access$2300(ActivityThread.java:125)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4627)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:876)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:634)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassNotFoundException: com.my.app.SoundMachine in loader dalvik.system.PathClassLoader[/mnt/asec/com.my.app-1/pkg.apk]
at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:243)
at java.lang.ClassLoader.loadClass(ClassLoader.java:573)
at java.lang.ClassLoader.loadClass(ClassLoader.java:532)
at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2577)
... 11 more

These are the first couple of lines from my activity:

public class SoundMachine extends Activity {
  private SoundManager mSoundManager;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

EDIT: This is the (almost) complete onCreate:

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    mSoundManager = new SoundManager();
    mSoundManager.initSounds(getBaseContext());

    int counter = 0;
    for (Integer soundFile : soundFiles) {
      counter++;
      mSoundManager.addSound(counter, soundFile);
    }

    ImageButton SoundButton1 = (ImageButton) findViewById(R.id.sound1);
    SoundButton1.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {
        mSoundManager.playSound(1);
      }
    });
    SoundButton1.setOnLongClickListener(new OnLongClickListener() {
      public boolean onLongClick(View v) {
        saveSoundChoice(soundFiles[0], soundNames[0]);
        return true;
      }
    });

(...more of this...)

    Button StopButton = (Button) findViewById(R.id.stopbutton);
    StopButton.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {
        mSoundManager.stopAll();
      }
    });
  }

And here's my manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.my.app" android:installLocation="preferExternal"
    android:versionCode="9" android:versionName="1.2">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".SoundMachine" android:label="@string/app_name"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-sdk android:minSdkVersion="3" android:targetSdkVersion="8" />
</manifest>

So all possible errors I already read about here and in some forums don't apply to my app.

  • The activity is present in the manifest.
  • The super-method is called in the overriden method.
  • The ContentView is set before accessing elements in the view.

I know it's hard to pinpoint the source of an error without being able to reproduce it, but maybe somebody has a bright idea and can help me out.

Some questions:

  • Do I need the "intent"-part in the manifest? Eclipse created it when I created the project. (Yes, according to Mayra)
  • Should the super-method be called where it is? (Yes, according to Mayra)

EDIT: The main question that remains now is: How come the path in PathClassLoader is different from my package-name? The page John J Smith posted seems to deal with the same problem, but I don't understand the fix that was applied there.

Thanks, Select0r

Weiland answered 27/1, 2011 at 18:55 Comment(8)
This only happened to a single user? Do you know what hardware, sdk version, etc?Dunlop
Can you show the rest of onCreate?Dunlop
To answer your questions: Yes, calling the super first should be fine. And yes, the intent-filter is necessary to have your app have a launcher icon. See developer.android.com/guide/topics/intents/intents-filters.htmlDunlop
@Mayra: I don't know how many users this happened to, I just get the report in the Android market (there's one report but there may be lots of others who just didn't send a report). Unfortunately the report doesn't tell me anything about the configuration the user uses. I have edit my question containing (almost) all of my onCreate-method. Thanks for your answers.Weiland
Can you show a rest of manifest file, or just a top section where the "manifest" tag is declared?Shannan
I have edited my original post to show the whole manifest.xml.Weiland
Is your SoundMachine class is in com.my.app package?Shannan
Yes. The app contains two classes and both are in the same package (com.my.app).Weiland
M
38

I solved this problems by selecting : Project->properties->order and export

select the all external jar files. clean and build it solved the issue

Malodorous answered 31/5, 2012 at 19:52 Comment(4)
Project->Properties->Java build path->order and exportExothermic
damn this should be the answerGriswold
For Android Studio this would be Project Settings > Modules > [Project to be tested] > DependenciesAttalanta
Yes!! This worked for me too. I also had to remove the same jars that I had added under Project->Properties->Java Build Path->Libraries, otherwise I got the exception "Multiple dex files - Conversion to Dalvik format failed".Rafaelita
C
38

Since ADT update to revision 22 (May 2013) you have to check "Android Private Libraries" check box in Project -> Properties -> Java Build Path -> Order and Export in Eclipse for your older projects to get rid of this exception ...

Civism answered 3/6, 2013 at 21:38 Comment(3)
Worked, but had to do a clean after checking it. Upgrading Android tools is always scary. There's always something broken.Ligule
android tools -> fix project properties, automatically checked it for me.Hyper
Does anyone know how to fix this in an IntelliJ / Android Studio Gradle setup?Soldier
F
20

I just got the same error (Unable to instantiate activity...) with Opera Mini. Opera Mini was on SD card (moved to SD card in the app setting). The error seems to be related to the fact that I swapped the SD card yesterday. The device was shutdown, I copied all data from the old card over to the new card (with cp -a) and then inserted the new card and started the device again. Everything seems to work as expected, but I see now that all apps on the SD card crashes with the same error.

  • Device: HTC Desire HD (Android 2.2)
  • Old SDHC card: SanDisk 8GB class 4
  • New SDHC card: Kingston 16GB class 4

So I would say that this is a an Android bug and not something that can be fixed by app developers.

Also see: http://android-developers.blogspot.com/2010/07/apps-on-sd-card-details.html

It has always been the case that when you swap SD cards on an Android device, if you physically copy the contents of the old card to the new one, the system will use the data on the new card as if nothing had changed. This is also true of apps which have been installed on the SD card."

This seems to be incorrect.

Fantasm answered 3/2, 2011 at 9:2 Comment(3)
That could be a reason that I can't reproduce the error, as I don't have Froyo and can't install apps on SD. On the other hand it sounds strange that people will report this issue in the market ... because what do you do, after you downloaded an app? Start it, I'd think, not move it around and shuffle SD-cards. But it's still something to keep in mind, thanks for pointing it out. The market should really allow to communicate with people that leave comments directly to get rid of this wild guessing ...Weiland
Many users have app2sd installed. This app notifies you if the newly installed app can be moved to the SD card. However, I can't reproduce this issue by simply moving the app to SD card (tried HTC Desire HD, Nexus One and Samsung Galaxy Tab).Fantasm
Thanks for checking it out! Even though it bugs me, I guess I'll have to stick with the believe that this hardly ever happens and that I can't really do anything about it ...Weiland
I
7

This happened to me when I refactored one of my package names and the refactor tool removed the leading "." from all of my activity names. so in the AndroidManifest.xml, I had to change android:name="MyActivity" to android:name=".MyActivity"

hope this helps someone, I just wasted a bunch of time o

Ichnography answered 23/5, 2011 at 4:38 Comment(1)
Update your eclipse android plugin to >r12 and this won't happen again.Areopagite
C
6

This doesn't apply to the OP's question, but it did to mine and it took me quite some time to figure it out: when using the Google Maps API, make sure you've included the library declaration in the application manifest.

For instance:

public class MyActivity extends MapActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }

}

In AndroidManifest.xml:

<application>
    <uses-library android:name="com.google.android.maps" />
    <activity android:name="MyActivity" android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
Cribble answered 12/10, 2011 at 12:8 Comment(1)
This is what I was searching forCitric
C
4

I don't know why the path in the PathClassLoader is different to your package name but when testing on the emulator try forcing a close then run it again, as per this link

Carcinogen answered 27/1, 2011 at 19:35 Comment(5)
Tried it, but it didn't crash. Not in the emulator, not on my phone.Weiland
I read and re-read that article but, to be honest, I don't really get what is meant by "static application reference" in that post or why "the classname should have been changed", can you help me out?Weiland
I would try changing from getBaseContext() to this or getApplicationContext() as described in more detail here: #1027473 If you follow the links in this article to Romain Guy's article, you can see the importance of the context when getting resources and I think it's worth investigating. I presume the 'static application reference' is also talking about the static call to get the context.Carcinogen
That really does make sense, thanks. I never questioned that method as it was copied from a soundboard-tutorial and always worked for me. I'll try and investigate if I can reproduce the error and whether it'll be fixed when exchanging the context.Weiland
Unfortunately I'm still not able to reproduce the error. I gave it a shot with getBaseContext removed. I'll see how the market responds :)Weiland
B
4

I had the same problem of you and, after hours of search, I discovered something interesting. I'll try to expose that as clearly as possible:

  • I created a project with a package called "myapp.sound" containing the activity. Program ran normally;
  • I renamed that package calling it "app.soundapp" and program still ran normally.

However, in the manifest.xml file of the program there was something strange: the name of package was the old "myapp.sound". I changed manifest with correct new name and, from that moment on, our error occured. I don't know why, but seems that the "package name changer" of Eclipse doesn't update all the dependencies. If it's not strictly necessary, don't rename the package containing activity. Maybe, to solve your problem you have to create a new project and copy inside it all your java class.

Butadiene answered 8/5, 2012 at 13:53 Comment(0)
D
4

Look at the package defined at the top of the manifiest file and make sure that it matches the package where you class is defined.

My problem was that I did not have matching package names.

Also enusre that you have a folder named "libs" with an 's'. Put all of you jar files that you added inside it and add to build path.

Delaunay answered 20/9, 2012 at 21:9 Comment(0)
C
3

This problem can also occur if you have a constructor with one or more parameters in your activity class.

Cloutman answered 4/8, 2011 at 17:48 Comment(1)
You sir, deserve a medal! Thanks for the tip.. I was struggling for hours.Illeetvilaine
D
3

This problem might exist when you change the name of your class and update the manifest file and the manifest file is not updated on the emulator. Try uninstall the application from emulator and then reinstall it. This will work.

Diageotropism answered 16/11, 2011 at 14:8 Comment(0)
C
3

I was coming across this problem when I was including java Projects in my buildpath for my android project targeting JavaSE-1.7.

For some reason my emulator would not throw a class not found if the java project it was including was originally created targeting JavaSE-1.6. Eclipse would give me a warning "Build path specifies execution environment JavaSE-1.6. There are no JREs installed in the workspace that are strictly compatible with this environment." But the Android emulator would launch and I would not get a classnotfoundexception

So if you are including projects that target JavaSE-1.7, remake them targeting JavaSE-1.6 and this may solve your problem.

Good luck!

Caerphilly answered 12/12, 2011 at 23:21 Comment(0)
L
3

Similar to Bobf Cali, I first saw this error after renaming my base package to change the "example" section. To fix it, I had to delete my gen and bin directories, clean the project, and rebuild.

Note depending on what version of the eclipse android plugin you're using (if any), you may also have to update activity names in your AndroidManifest.xml

Lexy answered 30/1, 2013 at 2:20 Comment(0)
S
3

Saw the same error message after doing a simple upgrade of my app. Fixed it by doing this:

Project->Build automatically OFF
Project->Clean->Selcting my project

Then I did a new export of my signed app, and it worked.

Shipowner answered 21/6, 2013 at 8:34 Comment(0)
B
2

Are you sure your package name is unique? I don't know what happen if the user has another app using the same package name, but maybe it can cause strange errors like this.

EDIT: I just saw this page, it remembers me I already had this problem when downloading an app from the Android market. The app crashed on startup, I tried a lot of times but I always ended with the same result. Then I tried to uninstall the app, reinstall it, and everything worked fine. I'm still using it today and the problem never happened again.

On my link, you can also see that they reproduced your error by making the app unreachable (unmount SD), so it's definitely not a problem with your code.

Bernt answered 31/1, 2011 at 18:12 Comment(2)
The package name will be unique, I'm pretty sure. I'd like to believe that the error is not in my code, thanks for the link, but the error-message is so strange, showing a different path all at a sudden. Even if that's the error, how are you going to tell the user? They'll downrate the app and uninstall it right away...... another idea: could this be connected to the fact that the app is rather big (>1MB) as it contains lots of sounds? (just taking wild guesses, I'm really helpless)Weiland
1MB is not so big... I published a 3.6MB app and never saw this error. By the way here is the link to the full thread of the link I posted before : groups.google.com/group/android-developers/browse_thread/thread/… They talk a lot about your problem. Maybe you will find something useful...Bernt
A
2

Check out this article: http://www.androidguys.com/2010/05/22/storing-apps-sd-froyo/ which explains the limitations of storing apps on SD cards. If your users have their SD card mounted by a computer, that might make the SoundMachine class invisible. And I wonder if the cp command fails (perja's attempt to fix) because it might change the ownership of the files such that the userid of the app and the ownership of the files don't match anymore.

Agonizing answered 5/2, 2011 at 16:48 Comment(0)
Q
2

I had the same issue in a recent Android project. The problem turned out to be pretty simple yet it was hard to locate. This happened to me then I refactored the package name of the entry point activity of the app. This created a conflict with the gen/.../R.java file, since the package there was not refactored. Eclipse did not complain, but at runtime i got the same error you posted: could not instantiate... classNotFoundException...

Lesson learned from this: do NOT refactor the package name that holds your main activity!

Hope this helps you or anyone breaking his/her head over this error!

Quantize answered 4/11, 2011 at 16:58 Comment(1)
This is the answer that helped me. I had to copy the classes and layouts of the module, delete it and create a new module with a new name. Luckily the module was a small one.Punnet
U
2

I solved this and could locate the causes: -The Manifest will be corrupt. Even if the package-structure is right and every single data was written down correctly the activity will not be found. -R will be in the package-structure which was first declared before renaming. -The run-configurations are setup with the wrong package of R. So the activity can't be found.

What we have tried: -Manually editing the run-configs via export/import -Manually renaming the package-structure -Manually renaming the R-package-structure -Deleting the run-config (it will be rebuild if you try to start the app)

Solution: Try to setup a new project without reusing your manifest. I have tried to reuse it and got the same problems all over again. So after the main cause has to be the corrupt manifest. I hope this helps!

Unbalanced answered 21/12, 2011 at 0:53 Comment(0)
S
2

Maybe it is too late to solve your problem but hopefully it will help someone else.
I had a similar problem and after many tries, I decided to delete R.java.
That did the trick.

Snook answered 22/6, 2012 at 9:49 Comment(0)
G
2

Make sure your /src dir is listed in your projects>properties>java build path>source

Gariepy answered 11/9, 2012 at 0:14 Comment(0)
B
2

This error can also occur when you (at the project level) incorrectly Import > Android > Existing Android Code Into Workspace, via Eclipse. In my case, this resulted in an empty "src" folder, but then I noticed new folder starting with "java" at the root and continuing with the package path (i.e. com/zyzcorp/...), leading to the MainActivity.java file.

To test what I thought may fix the problem, I copied the com.*.MainActivity.java file into the src folder, refreshed, cleaned, and restarted Eclipse. I was able to build and run the app on the target device.

Barrel answered 13/12, 2013 at 21:1 Comment(0)
D
1

I don't see anything obviously wrong. All I can say is to try to test it in as many different configurations as possible.

Test it in the emulator for every possible SDK level, follow the guidelines for testing on different sized screens (although that doesn't seem to be your problem).

Try to test it on a phone from each of the major providers, if you can find friends that have them: HTC Sense, Motoblur, etc.

If you only get one report, it might just be something screwy with that guys device. See if you get other, similar reports that add more data.

Dunlop answered 27/1, 2011 at 19:16 Comment(1)
I tried all SKD-levels and will go for the screen resolutions. On actual devices I could test 1.6, 2.1, 2.2 as well as different manufacturers, but it always works. I don't think the one report means that only one guy has this problem as I have received market-comments that say it crashed, only the one guy sent in the stacktrace-log.Weiland
B
1

You had renamed the package anytime? This normally happens if the package was renamed after creation. Following link should be helpfull in that case http://code.google.com/p/android/issues/detail?id=2824. If this is not the case,please post your complete manifest file.

Batista answered 1/2, 2011 at 14:12 Comment(1)
I had problems renaming a package with some other app, but I was never able to even compile the app until those errors were fixed, so this won't be the problem here (especially as I didn't rename this one).Weiland
W
1

I has the same problem but this fixed it. In my androidmanifest.xml i had this line called android:name = myappnameActivity. Although my class name was just myappname. Hence i took off the Activity part in the xml file and all was fine.

Wilkins answered 12/4, 2012 at 15:31 Comment(0)
E
1

I had 5 different packages. And for some reason the compiler was looking for the activity on the wrong package.

So I switched my activity and all the class that inherits the activity to the package that it was looking into.

I got the name of the package it was looking for in the beginning of the logcat.

Embryo answered 12/7, 2012 at 21:56 Comment(0)
E
1

I was just having a problem with this myself, so I want to bring up what caused the problem for me. I had just included some new libraries setting up expansion APKs. The libraries are dependant on each other and I was only including one of them in my properties > android > libraries.

So this could happen if the user is missing a library on their phone that most users have.

It showed ClassNotFoundException on my main activity because it implements a class which was in the missing library.

Erst answered 28/9, 2012 at 4:15 Comment(0)
E
1

I fix this problem by deleting "bin" and "gen" folder, and rebuilding project.

Elberfeld answered 15/5, 2013 at 7:44 Comment(0)
D
1

I had the same problem I solved it by uncheck the Android Dependencies from Project--> Properties-->Java builder Path-->android dependencies

Detergency answered 1/11, 2013 at 15:0 Comment(0)
V
0

Delete BIN and GEN folder files. Rebuild, everything should work. Check if theres another error below the "unable to instantiate", sometimes another error is firing this (activity cant load because of something even if its class has been found.

Vaud answered 7/8, 2014 at 17:15 Comment(0)
A
0

What I had to do is just re-do the building/exporting process with no modification to the code whatsoever. It worked for me, which I did was to export it two times. On my first export, the build APK has lower file size and the second export (with no any modification to the code/configuration) produced a slightly larger file size (about 200KB diff).

This bug in building is really costly, kills you in front of your manager, and should be really fixed by Android/Eclipse team. Kind of sucks

Ap answered 13/8, 2014 at 7:59 Comment(0)
E
0

After spending 6 hours on this issue, found that it was a silly mistake. Apparently if you're defining your Application class in android manifest and you have enabled MultiDex enabled, you have to add that on Application Class. Here is example from my app.

It only gave me error on devices running on < Android 5.0

AndroidManifest.xml

 ......
 <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme"
        android:name=".AppClass"
.........

AppClass.java

class AppClass : Application() {
    override fun onCreate() {
        super.onCreate()
    }



    override fun attachBaseContext(base: Context) {
        super.attachBaseContext(base)
        MultiDex.install(this)   //Don't forget this !!!!
    }

}
Elector answered 28/2, 2020 at 15:44 Comment(0)
U
0

To solve this problem, we need to change the MainActivity.kt or MainActivity.java the following code:

package com.example.yourapp
Untruthful answered 24/12, 2020 at 5:34 Comment(0)
H
-1

I recently purchased a new tablet for development only with Android 4.0. It did not have an external SD card. The demo program I was running would crash with the same error. It had the same line in the manifest asking for SD permission:

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

After installing an external SD card, the problem went away. It is possible the person does not have an SD card and your software is not handling it properly. My demo program does not check for the existence of an SD card. Here is a stackflow link describing the issue:

Android development - test for SD card or assume it's there?

I realize I am late to the party, but this may help someone else.

Hammurabi answered 29/4, 2013 at 14:55 Comment(2)
The question is talking about ClassNotFoundException, how does it relate with sd card permission?Moreta
It might have something to do with it. see Perja's answer.Swish

© 2022 - 2024 — McMap. All rights reserved.