Question

I have an application. The main activity has a page that has a button. This button only opens another activity. Here's the problem though. When I do this in the portrait mode, it works perfectly. Even after the activity has started, I can change it to landscape mode and it works fine. The application only crashes when the first activity is in landscape mode and I click the button to start the new activity. Any ideas how I should fix this? Why is it not working only during startup? and why is it working fine in landscape mode after I start it in portrait mode?

Another interesting thing I noticed, I deleted the layout xml files in the landscape folder and it doesn't crash anymore.

04-26 15:09:50.558: E/AndroidRuntime(7034): FATAL EXCEPTION: main
04-26 15:09:50.558: E/AndroidRuntime(7034): Process: com.example.msapp2, PID: 7034
04-26 15:09:50.558: E/AndroidRuntime(7034): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.msapp2/com.example.msapp2.exercises.WorkoutBuddy}: java.lang.NullPointerException
04-26 15:09:50.558: E/AndroidRuntime(7034):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
04-26 15:09:50.558: E/AndroidRuntime(7034):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
04-26 15:09:50.558: E/AndroidRuntime(7034):     at android.app.ActivityThread.access$800(ActivityThread.java:135)
04-26 15:09:50.558: E/AndroidRuntime(7034):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
Was it helpful?

Solution

Chances are what's going on is that you are probably getting a reference to a layout element that exists in your portrait (/layouts/activity*.xml) layout but doesn't exist in your landscape layout (/layouts-land/activity*.xml).

For example,

Button button = (Button) findviewbyid(R.id.myButton);

Might work if you're in portrait because you have a <Button /> element in it. But your landscape layout does not have the same element.

This leads to a NullPointerException which is the exception you got. It occurs when you try to access an object that has not been initialized. So look out for where you are doing that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top