c# – AndroidGameWindow.SetDisplayOrientation NullReferenceException-ThrowExceptions

Exception or error:

I developed a game for Android using MonoGame & Xamarin. I incorporated BugSense into it and quickly started getting the following exception stack trace:

System.NullReferenceException: Object reference not set to an instance of an object
at Microsoft.Xna.Framework.AndroidGameWindow.SetDisplayOrientation (Microsoft.Xna.Framework.DisplayOrientation) <0x001c4>
at Microsoft.Xna.Framework.AndroidGameWindow.SetOrientation (Microsoft.Xna.Framework.DisplayOrientation,bool) <0x00097>
at Microsoft.Xna.Framework.OrientationListener.OnOrientationChanged (int) <0x001c7>
at Android.Views.OrientationEventListener.n_OnOrientationChanged_I (intptr,intptr,int) <0x0003f>
at (wrapper dynamic-method) object.ed9d7c7c-f3e6-4d7a-9249-1a139a251aed (intptr,intptr,int) <0x00043>

This is how my activity is setup:

[Activity(Label = "My Cool Game"
        , MainLauncher = true
        , Icon = "@drawable/icon"
        , Theme = "@style/Theme.Splash"
        , AlwaysRetainTaskState = true
        , LaunchMode = Android.Content.PM.LaunchMode.SingleTask
        , ScreenOrientation = ScreenOrientation.Portrait
        , ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.Keyboard | ConfigChanges.KeyboardHidden)]

And in the game constructor I have the following:

public Game1()
    _graphics = new GraphicsDeviceManager(this);
    _graphics.PreferredBackBufferFormat = SurfaceFormat.Color;
    _graphics.IsFullScreen = true;
    _graphics.SupportedOrientations = DisplayOrientation.Portrait | DisplayOrientation.PortraitDown;

The project is set to compile against v2.3. I haven’t had any issues relating to an orientation on my test devices so I am not sure what is causing this exception, hence I cant fix it.

How to solve:

I have come across this Null Reference exception before working on a different project. You will have to pardon my ignorance of your particular field in gaming but let me explain to you what this means perhaps it will help you solve this problem. What this exception means is that there is no object of a particular sort available in memory for the system to be able to work on it. An instance of this object must be created with the new keyword or in other ways for it to be recognised as a valid object in memory.

From reading the above error message it seems to want an object to initalise the display orientation. No where in your constructor or activity setup do I see anything creating any object for display orientation. Thus the object is not there in memory so it is null.

Leave a Reply

Your email address will not be published. Required fields are marked *