42

I've been having this problem for almost 2 months now and can't figure it out. The problem is that if my application is running and I run (reinstall) my application from Eclipse, I get an error message indicating that my application has crashed 'Unfortunately, has stopped.'. I notice that it also occurs when I run it away from my PC/Eclipse, I think that it happens only after I don't run it for a while.

It only occurs if the app is active in the 3rd activity (BaseDiagramActivity) and then I run the app again from Eclipse. I've stripped out basically all the application except the 3 activities and It's still happening.

I've searched and searched for a solution to this problem but can't find any good answer or one that applies to me.

It doesn't seem like a hardware or android version issue as I'm running this on my tablet (4.0.3) and my phone (4.0.2, was happening on 4.0.1 before update). Unless of course it is an ice cream sandwich bug.

Let me know if any more info is required.

The exception (Tag=AndroidRuntime)

FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to instantiate application android.app.Application: java.lang.NullPointerException
   at android.app.LoadedApk.makeApplication(LoadedApk.java:482)
   at android.app.ActivityThread.handleBindApplication(ActivityThread.java:3938)
   at android.app.ActivityThread.access$1300(ActivityThread.java:123)
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1185)
   at android.os.Handler.dispatchMessage(Handler.java:99)
   at android.os.Looper.loop(Looper.java:137)
   at android.app.ActivityThread.main(ActivityThread.java:4424)
   at java.lang.reflect.Method.invokeNative(Native Method)
   at java.lang.reflect.Method.invoke(Method.java:511)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
   at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
   at android.app.LoadedApk.initializeJavaContextClassLoader(LoadedApk.java:362)
   at android.app.LoadedApk.getClassLoader(LoadedApk.java:305)
   at android.app.LoadedApk.makeApplication(LoadedApk.java:474)
   ... 11 more

The Android Code

LoadedApk.initializeJavaContextClassLoader() - Line 362 seems to be the offender

Below are the relevant files:

AndroidManifest.xml

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

    <uses-sdk android:minSdkVersion="14" />

    <application 
        android:icon="@drawable/ic_launcher" 
        android:label="@string/app_name" >
        <activity 
            android:name="HomeActivity" 
            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="LoadDiagramActivity" android:label="Load Diagram"></activity>
        <activity android:name="BaseDiagramActivity" android:label="Base Diagram"></activity>
    </application>

</manifest>

HomeActivity.java

public class HomeActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.home);

        Button diagramButton = (Button)findViewById(R.id.diagram);
        diagramButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                startActivity(new Intent(HomeActivity.this, LoadDiagramActivity.class));
            }
        });
    }
}

LoadDiagramActivity.java

public class LoadDiagramActivity extends Activity {

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

        ActionBar actionBar = getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.load_diagram_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
            case R.id.add_new_diagram:
                startActivity(new Intent(this, BaseDiagramActivity.class));
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}

BaseDiagramActivity.java

it doesn't actually matter what activity this is, the exception occurs as long as a 'third' activity is started (or clicking the add button on LoadDiagramActivity.

public class BaseDiagramActivity extends Activity {
}

home.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/diagram"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Diagram" />

</LinearLayout>

Additional information

When I stripped down my project in order to ask a simpler answer, I moved everything into the package's namespace. In the actual project there are 5 namespaces, they were still present when I was testing with the stripped down version however just not called (as far as I could see).

Here are the packages:

  • [package] - general logic
  • [package].activities - all activities and base activities
  • [package].database - all interaction with the database
  • [package].models - models for saving/loading data
  • [package].renderables - objects drawn to a canvas

I have tried to add an `android:sharedUserId' attribute to the manifest and and it seemed to do nothing both times I tried. When I was initially investigating this I came to the conclusion that the shared user id only applied to different projects, not different packages.

Also I don't believe there was any interaction with the database when I stripped everything down. The fact that the 3rd activity could be any activity, even HomeActivity, was something against this theory.

Useful links

Update 1/11/2012

Last couple of days I've jumped back into this project, I created a brand new project in Eclipse Juno (was on Helios before) and transferred everything over manually so that Eclipse and Android tools handled almost all of the Manifest interaction but it's still occurring. I will look at it a bit more over the next few days and update if I find anything.

FYI my new project is targeting the following:

<uses-sdk
    android:minSdkVersion="14"
    android:targetSdkVersion="15" />

The new project structure also has all the activities in the root package now (ie. [package], not [package].activities). I'm also using the (new?) syntax to show the parent activity:

<meta-data
    android:name="android.support.PARENT_ACTIVITY"
    android:value="[my package].LoadDiagramActivity" />

It is also still occurring on my now updated Galaxy Nexus running Jellybean 4.1.2.

Community
  • 1
  • 1
Daniel Imms
  • 47,944
  • 19
  • 150
  • 166
  • Can you provide simple app code on Github or somewhere else? – Jin35 Apr 03 '12 at 07:07
  • I can't very easily right now as I just moved and am stuck without internet on my desktop (which lacks wireless). Using my phone to post this. I believe the code should work if you just create those files in an eclipse project. – Daniel Imms Apr 03 '12 at 08:49
  • Try replicating this behaviour on HoneyComb or GingerBread, it is probably a [bug](http://code.google.com/p/android/issues/detail?id=25869&can=1&q=LoadedApk.makeApplication&colspec=ID%20Type%20Status%20Owner%20Summary%20Stars) in ICS though. – yorkw Apr 03 '12 at 23:44
  • Regardless of whether it works in 2.3 or 3.0, it won't really solve the issue though. I wasn't even planning on targetting less than 4.0 anyhow. [One of the useful links](http://stackoverflow.com/questions/9039017/android-app-application-cannot-be-instantiated-due-to-nullpointerexception) seems to target version 8 as minimum SDK version. – Daniel Imms Apr 04 '12 at 00:28
  • Could you please test it again, then post all error logcat (which I think there are more after `... 11 more`)? Or can you run `adb bugreport` and attach the file somewhere, then give me the link? –  Apr 04 '12 at 17:03
  • 1
    `... 11 more` is the last error/red line in logcat. – Daniel Imms Apr 05 '12 at 01:04
  • A common error when it comes to interpreting errors from the OS itself is that often there is a warning above the error in the log. I would scroll up and see if you can find an unusual log entry that only occurs in that circumstance. I have seen them even be at the info level, though it is rare. It often gives the hint that is needed. (One such log entry was "Unexpected Resume on Activity ... when it is already resumed." Caused me a lot of crap. Fixed it though :) – Fuzzical Logic Apr 09 '12 at 11:31
  • @FuzzicalLogic The warnings above the exception are: TextLayoutCache : computeValuesWithHarfbuzz -- need to force a single run, AND dalvikvm (same PID) : threadid=1: thread exiting with uncaught exception (group=0x40a621f8) – Daniel Imms Apr 14 '12 at 04:12

9 Answers9

9

Try adding one more thing in Manifest file, I am sure you have already tried..

<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="[my package]" 
    android:versionCode="1" 
    android:versionName="1.0"
    android:sharedUserId="com.mj.app" > 

It seems like in your project you have multiple PACKAGES, like com.package.p1 , com.package.p2 ,com.package.p3..

And while starting you are in p1 and then moves on to p2 - p3... and at that time you try to run it again..so the Android gives you error.

MKJParekh
  • 34,073
  • 11
  • 87
  • 98
  • This is one of the things I investigated prior to asking on stackoverflow. There is a little problem with your `sharedUserId` as it must have at least a period in the name I noticed when trying it again now. My project is actually split up into 5 packages, which I'll explain in more depth at the bottom of the question. I have my doubts about this though as when I was asking the question I stripped most of the project out and put it all into the project's namespace and it still occurred. This is basically what the exception in the android code is complaining about however. – Daniel Imms Apr 06 '12 at 23:14
  • 1
    The exception stack trace is exactly same as the one in [this similar question](http://stackoverflow.com/questions/10150899/runtimeexception-unable-to-instantiate-application), see if my answer there helps. – yorkw Oct 31 '12 at 21:54
  • @yorkw A really good answer..But in my case it's getting force closed..with the same error..while I am running my app changing the orientation 5-6 times moving through different activity..so I require the solution to overcome this error. – MKJParekh Nov 01 '12 at 06:29
  • As far as I can tell, this exception itself may not cause your app crash, however, as I explained in the related question, it is trying to reuse or recycle the previously opened activity/view, so I would double check all my construction/deconstruction code and see if components are properly initialized/created and destroyed/finished within the correct running life cycle, for instance, when device is rotated which cause Activity destroyed and recreated at some condition. – yorkw Nov 07 '12 at 00:11
  • @MKJParekh what should i assign to "sharedUserId"? can you please explain your answer for newbies like me? – M. Usman Khan Mar 06 '14 at 10:45
2

If you put 13 in your minSdkVersion, it should work.

Either that, or you need to setDisplayHomeAsUpEnabled(false) in the onCreate() of your other activities.

Both those solutions should work.

Starting at API Level 14 according to the documentation, the setHomeButtonEnabled(true) is no longer done for you by default, and it goes on to say that

Setting the DISPLAY_HOME_AS_UP display option will automatically enable the home button.

So we can infer that setDisplayHomeAsUpEnabled(false) works in a similar way as setHomeButtonEnabled(false)

Stephan Branczyk
  • 9,363
  • 2
  • 33
  • 49
  • I couldn't get either method to work. Same result for all, I tried commenting out all interaction with the `ActionBar`, adding the `DISPLAY_HOME_AS_UP` flag, setting `setDisplayHomeAsUpEnabled(false)`.I still have some hopes for the SDK version as I haven't got version 13 downloaded just yet so I wasn't able to target anything less than 4.0 – Daniel Imms Apr 04 '12 at 07:37
  • Downloaded 13 and targeted it in addition to setting to min SDK, after removing ICS-specific stuff, the same exception, occurred. – Daniel Imms Apr 04 '12 at 21:51
2

If I am not mistaken, this only happens when we reinstall the app from Eclipse Run->As. So this is unlikely to happen when a user upgrades through Play. I can say this with confidence since I did notice my app too with this exception during reinstall through Eclipse, but nothing on Crittercism.

To fix this, I worked on resolving memory consumption of my app.

  1. If you only have 1 set of drawables, then change that. Create a drawables-mdpi and copy all the file from that 1 drawables folder (drawables, drawable-ldpi). If you have just 1 set, Android will resize it for its use on bigger screens, thus internally taking up too much memory, and cleanup of this kind of memory (bitmap) is bug prone. Sound crazy, but does wonders. Dont believe me, run it under Heap memory usage watch before and after this change, you will notice that your app is taking 25% less memory for a common scenario.
  2. If you are doing any Bitmap operations, you may want to consider downscaling. Atleast when you are setting options you definitely want to downscale it. Check here and here. Search or downscaleing.
  3. Finally dont forget to bitmap.recycle(); bitmap = null; in your onDestroy and before all System.exit(0).

Android does a lot of background work, and reinstallation is a abrupt cleanup expectation from the app. Memory not cleaned up can cause issues. This exception is one of those internal ones. So dont think of it to be straightforward.

Community
  • 1
  • 1
Siddharth
  • 9,349
  • 16
  • 86
  • 148
  • I'll check it out tonight if I get time. It's not just running from Eclipse, it also happens when I open the app, use other apps and then come back (when it can't resume and needs to restart I assume). – Daniel Imms Nov 05 '12 at 22:21
  • Its a bitmap issue most probably. I haven't seen what you have until now. But exception looks similar. Its a bitmap.recycle, null issue I think. – Siddharth Nov 06 '12 at 02:31
  • @Siddharth In my case this answer is not at all related, the error occurs while having multiple packages having activities and running app and moving from one to another and changing orientations and coming back and forth. – MKJParekh Nov 06 '12 at 05:15
  • Changing orientations is when Android does a lot of resizeing and assumptions about layout positioning. The drawables thing is absolutely necessary. Do this, run a scenario while watching your heap memory. Do this one change and rerun your scenario, watch your heap again. If this does not help, I'll take back my answer. – Siddharth Nov 06 '12 at 06:48
0

Wait after your application crashes when u run it second time. The app will launch after the crashing again. This happens sometimes with me. If the same is the case with u dont forget to clean your project everytime before u run it.

Chandrashekhar
  • 498
  • 4
  • 19
0

By inspecting your code I feel you are skipping to set "setContentView(rid)" in LoadDiagramActivity. Please try setting the view in onCreate().

Hope this will help you.

Ajay Kumar Meher
  • 1,932
  • 16
  • 24
0

You need to append "." before the activity name in Menifest.

Like this

<?xml version="1.0" encoding="utf-8"?>

<uses-sdk android:minSdkVersion="14" />

<application 
    android:icon="@drawable/ic_launcher" 
    android:label="@string/app_name" >
    <activity 
        android:name=".HomeActivity" 
        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=".LoadDiagramActivity" android:label="Load Diagram"></activity>
    <activity android:name=".BaseDiagramActivity" android:label="Base Diagram"></activity>
</application>

I update your menifest's activity. Please check it...

V.J.
  • 9,492
  • 4
  • 33
  • 49
0

There is nothing wrong with the code you've given us so far. I just tried it in a new project with the package name com.test and it worked flawlessly. The only thing I added in the files were the package declaration. (And I added the load_diagram_menu.xml, of course.)

If possible, it would be great if you could give us access to the complete project. If the project is working on someone else's computer, it's most likely Eclipse or the Android Eclipse plugin-in that are misbehaving. A clean install of Eclipse would solve that. (Though I understand how being offline could make this difficult. :-) )

Albin
  • 4,180
  • 2
  • 27
  • 19
0

For this, be sure to have the "Build Automatically" checked when cleaning the project. (Project -> Build Automatically)

0

You haven't added the period to the names of your activities in manifest's android:name attributes. Perhaps, this causes the problem.

a.ch.
  • 8,285
  • 5
  • 40
  • 53