سؤال

I have some error reports on my Android app, it's a Nullpointerexception in onCreate() in an Activity. The code that fails is getIntent().getExtras().getStringExtra("name"). (Nullpointerexception)

That means that getExtras() is null somehow. I am sure that I am setting the intent extra on every place I am creating the intent. I can't recreate it on my emulator on device. I think it happened on my real device (but not while I was debugging) after I tried to open the app again, in the mean time Android probably killed the process and recreated the activity again. But shouldn't be the intent extras kept even in this scenario?

I tried to kill the process on the emulator, onCreate was called again and the getExtras() returned the right value.

I replaced the code with getIntent().getStringExtra(). What's the difference besides it won't throw a nullpointerexception but will still set the String as null. Is there any other difference?

What could be causing it?

هل كانت مفيدة؟

المحلول 3

I found out that somewhere else in my code I was creating shortcut intents which had a String[] extra. Android HOME (and maybe other parts of the system) don't persit string arrays, only primitive extras (int, string, long, float...). But the code that was causing problems doesn't use shortcuts, it's only a simple activity which receives a string array extra. Maybe the empty extras were caused by this problem too - the application was killed by OS and the extras could not be stored. No exception is thrown by Android in this case.

Described by Romain Guy here: http://groups.google.com/group/android-developers/browse_thread/thread/7f2ce458bd5d112f/189e2b7b2b2532d7

I asked a more specific question about this here: Shortcut intent extras lost after restart?

نصائح أخرى

Intent.getStringExtra() returns null if there are no extras. Intent.getExtras() returns null if there are no extras, so you need to check for that before trying to call getString() or other methods on it.

getIntent.getExtras() is returning null at some point. getIntent().getStringExtra() is most likely coded to check for a null extras and to return null if getExtras() is null. So called "no throws" architecture. If so, this is valid runtime execution and would not throw an exception. calling getStringExtra on a null extras is not valid runtime execution and should throw an exception.

It appears that there IS a path where getExtras() is null, so you could code around this by checking for a null extras.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top