developer tip

Android : 활동을 인스턴스화 할 수 없음 / ClassNotFoundException

copycodes 2020. 11. 7. 10:16
반응형

Android : 활동을 인스턴스화 할 수 없음 / ClassNotFoundException


최근에 시장에 앱을 게시했는데 일부 사용자로부터 오류가 발생합니다. 앱이 시작되면 바로 충돌 할 수 있습니다. 안타깝게도 그에게 직접 연락 할 수 없으며 앱은 내 전화 (및 일부 친구의 전화)뿐만 아니라 에뮬레이터에서도 잘 작동합니다.
편집 : "시작시 크래시"또는 "작동하지 않음"과 같은 의견을 시장에서 받았을 때 두 명 이상의 사용자에게 이런 일이 발생한다고 생각합니다. 이 스택 트레이스 하나만 받았지만 구성, 기기, Android 버전 등에 대한 정보가 없습니다.

이 앱은 단순한 사운드 보드이므로 마법이 전혀 필요하지 않지만 일부 휴대폰에서는 실패하는 이유를 알 수 없습니다. 내가 얻는 스택 추적은 다음과 같습니다. 누구나 나를 도울 수 있기를 바랍니다.

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

다음은 내 활동의 처음 몇 줄입니다.

public class SoundMachine extends Activity {
  private SoundManager mSoundManager;

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

편집 : 이것은 (거의) 완전한 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();
      }
    });
  }

그리고 여기에 내 매니페스트가 있습니다.

<?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>

따라서 여기와 일부 포럼에서 이미 읽은 모든 가능한 오류는 내 앱에 적용되지 않습니다.

  • 활동이 매니페스트에 있습니다.
  • 수퍼 메서드는 재정의 된 메서드에서 호출됩니다.
  • ContentView는 뷰의 요소에 액세스하기 전에 설정됩니다.

나는 그것을 재현하지 않고 오류의 원인을 정확히 찾아내는 것이 어렵다는 것을 알고 있지만 누군가가 밝은 아이디어를 가지고 있고 나를 도울 수있을 것입니다.

몇 가지 질문 :

  • 매니페스트에 "의도"부분이 필요합니까? Eclipse는 프로젝트를 만들 때 생성했습니다. (예, Mayra에 따르면)
  • 슈퍼 메소드가있는 곳에서 호출되어야 하는가? (예, Mayra에 따르면)

편집 : 지금 남아있는 주요 질문은 PathClassLoader의 경로가 내 패키지 이름과 다른 이유는 무엇입니까? John J Smith가 게시 한 페이지는 동일한 문제를 다루는 것 같지만 거기에 적용된 수정 사항을 이해하지 못합니다.

감사합니다, Select0r


프로젝트-> 속성-> 주문 및 내보내기를 선택하여이 문제를 해결했습니다.

모든 외부 jar 파일을 선택하십시오. 청소하고 구축하여 문제를 해결했습니다.


ADT가 개정판 22 (2013 년 5 월)로 업데이트 된 이후 로이 예외를 제거하려면 이전 프로젝트에 대해 Project-> Properties-> Java Build Path-> Order and Export in Eclipse에서 "Android Private Libraries"확인란 을 선택해야합니다. .


Opera Mini에서 동일한 오류 (활동을 인스턴스화 할 수 없음 ...)가 발생했습니다. Opera Mini는 SD 카드에있었습니다 (앱 설정에서 SD 카드로 이동). 이 오류는 어제 SD 카드를 교체했다는 사실과 관련된 것 같습니다. 장치가 종료되고 이전 카드의 모든 데이터를 새 카드 (cp -a 사용)로 복사 한 다음 새 카드를 삽입하고 장치를 다시 시작했습니다. 모든 것이 예상대로 작동하는 것 같지만 이제 SD 카드의 모든 앱이 동일한 오류로 충돌합니다.

  • 기기 : HTC Desire HD (Android 2.2)
  • 기존 SDHC 카드 : SanDisk 8GB 클래스 4
  • 새로운 SDHC 카드 : Kingston 16GB 클래스 4

그래서 저는 이것이 안드로이드 버그이고 앱 개발자가 고칠 수있는 것이 아니라고 말하고 싶습니다.

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

Android 기기에서 SD 카드를 교체 할 때 이전 카드의 내용을 새 카드에 물리적으로 복사하면 시스템이 새 카드의 데이터를 변경된 것이없는 것처럼 사용하는 경우가 항상 있습니다. SD 카드에 설치된 앱도 마찬가지입니다. "

이것은 잘못된 것 같습니다.


패키지 이름 중 하나를 리팩토링하고 리팩터링 도구가 선행 "."을 제거했을 때 이런 일이 발생했습니다. 내 모든 활동 이름에서. 그래서 AndroidManifest.xml에서 android : name = "MyActivity"를 android : name = ". MyActivity"로 변경해야했습니다.

이것이 누군가에게 도움이되기를 바랍니다. 나는 단지 많은 시간을 낭비했습니다.


이것은 OP의 질문에는 적용되지 않지만 내 문제를 해결하는 데 꽤 시간이 걸렸습니다. Google Maps API를 사용할 때 애플리케이션 매니페스트에 라이브러리 선언을 포함했는지 확인하세요.

예를 들면 :

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

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

}

에서 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>

PathClassLoader의 경로가 패키지 이름과 다른 이유를 모르겠지만 에뮬레이터에서 테스트 할 때이 링크에 따라 강제로 닫은 다음 다시 실행 하십시오.


나는 당신과 같은 문제를 가지고 있었고, 몇 시간의 검색 끝에 흥미로운 것을 발견했습니다. 가능한 한 명확하게 공개하려고 노력할 것입니다.

  • 활동이 포함 된 "myapp.sound"라는 패키지로 프로젝트를 만들었습니다. 프로그램이 정상적으로 실행되었습니다.
  • 나는 그것을 "app.soundapp"이라고 부르는 그 패키지의 이름을 바꾸었고 프로그램은 여전히 ​​정상적으로 실행되었다.

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.


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.


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


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.


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!


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


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.


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.


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.


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!


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


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.


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.


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.


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.


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!


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.


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.


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.


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


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


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.


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


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.

참고URL : https://stackoverflow.com/questions/4820554/android-unable-to-instantiate-activity-classnotfoundexception

반응형