Nullpointerexception and onPause(): a mystery
I'm writing a game on Android and this issue has stumped me. I overrode onPause() to enable the game to save its data to internal storage when it is not visible anymore. It works correctly until three or four times of pressing back or home. I get this instead:
Thread [<1> main] (Suspended (exception NullPointerException))
Main.onPause() line: 127
Main(Activity).performPause() line: 3842
Instrumentation.callActivityOnPause(Activity) line: 1190
ActivityThread.performPauseActivity(ActivityThread$ActivityRecord, boolean, boolean) line: 3335
ActivityThread.performPauseActivity(IBinder, boolean, boolean) line: 3305
ActivityThread.handlePauseActivity(IBinder, boolean, boolean, int) line: 3288
ActivityThread.access$2500(ActivityThread, IBinder, boolean, boolean, int) line: 125
BinderProxy(ActivityThread$H).handleMessage(Message) line: 2044
ActivityThread$H(Handler).dispatchMessage(Message) line: 99
Looper.loop() line: 123
ActivityThread.main(String[]) line: 4627
Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method]
Method.invoke(Object, Object...) line: 521
ZygoteInit$MethodAndArgsCaller.run() line: 868
ZygoteInit.main(String[]) line: 626
NativeStart.main(Strin开发者_如何学JAVAg[]) line: not available [native method]
The debugger states it blows up on this:
@Override
public void onPause() {
super.onPause();
Data data = game.writeProtoBuf(); // NullPointerException
try {
//IO stuff
writeProtoBuf doesn't actually write anything but is just a method to retrieve the game data and put it into the Data object. The debugger shows that game is null, but I don't see how that is possible when I can interact with the game correctly before closing it down. :/
Try using onSaveInstanceState instead of onPause
After much teeth-grinding, I think I have worked out the issue. I was assuming that the game instance would persist when changing activities. It doesn't, so that was why Android kept throwing up Nullpointer. I would start up the app, exit it (which causes it to save to internal storage), and then when I tried to save it again, it wouldn't work.
I fixed this by turning Game into a singleton, thereby preserving its state across activities. I admit I don't really understand why this works or how it works, but it works. If I sound really blur and confused, it's because I am. :P
Inspiration for the fix came from here.
精彩评论