views:

406

answers:

2

I have an Android app modeled after the LunarLander example by Google.

I am debugging it on a real device, (Motorola Droid) with Android 2.0.

When the orientation changes, the program crashes on a null pointer Exception.

Logcat from just before crash:

02-01 00:24:27.956: DEBUG/nate(8358): Starting Game
02-01 00:24:36.878: DEBUG/dalvikvm(1086): GC freed 1788 objects / 92256 bytes in 1389ms
02-01 00:24:38.542: INFO/WindowManager(1021): Setting rotation to 1, animFlags=0
02-01 00:24:38.558: INFO/ActivityManager(1021): Config changed: { scale=1.0 imsi=310/4 loc=en_US touch=3 keys=2/1/2 nav=2/2 orien=2 layout=34}
02-01 00:24:38.620: WARN/UsageStats(1021): Something wrong here, didnt expect org.nifong.leeder to be resumed
02-01 00:24:38.886: DEBUG/nate(8358): New Surface dimensions: 854x442
02-01 00:24:38.886: DEBUG/nate(8358): flies was null

The first line that worries me is "Something wrong here" at 24:38.620. I have no idea what it means, But I think its due to me not reacting properly to the screen change.

Next I get a debug message that I printed myself from within my own method surfaceChanged() about the new surface dimensions.

Then I print out debug message about whether flies was null. flies is the field that eventually causes the NullPointerException. Its created once, and never written to again for the rest of the program. I know that it was not null before the crash, because it was read several times.

Does anyone have a clue how my private member variable came to be null just by these clues?

I would include code but there is a lot of it and I don't know what would be relevant.

+1  A: 

I fixed it by adding these two lines to the activity tag in my manifest file

android:configChanges="keyboardHidden|orientation"
android:screenOrientation="landscape"

this says that my application will handle keyboard and orientation changes on its own (by doing nothing) and prefers to run in landscape all the time.

Nathan
This maybe a solution for your app, depending on your use case. In my view this is a rude behaviour forcing the user in a usage behaviour he maybe dislikes...
Janusz
+1  A: 

Orientation changes in Android affect state. Basically, your activity is destroyed and recreated. You must therefore be aware of what Android lifecycle events will be called and how to save state.

You also need to be wary of static instances and how that affects this lifecycle.

Here is a blog post explaining some of this.

JRL