Search code examples
androidnullpointerexceptionscreen-sizeandroid-windowmanager

Warning of Exception in windowManager.getDefaultDisplay() method


I am using this method below to get the actual width and height in pixels of the device screen inside onCreate() method of my Activity:

WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
Display display = windowManager.getDefaultDisplay();
Point point = new Point();
display.getSize(point);

int absolute_screen_width_in_pixels = point.x;
int absolute_screen_height_in_pixels = point.y;

Yet, I have this warning highlighting the possibility of a NullPointerException: enter image description here

I've never caught this Exception yet, and I can't think of a situation where it could happen. What should I do to ensure that this NullPointerException is never thrown?

Also, what backup code should I write to get the actual physical screen dimensions in case this method fails?


Solution

  • This is due to the fact that getSystemService(...) is internally annotated with @Nullable.

    In case you passed an invalid system service name (insted of WINDOW_SERVICE which is a constant in the Context class i believe pass "dummyName") it will return null.

    Since you're using a reference that is annotated as "might be null" (windowManager) to get some property (getDefaultDisplay()) hence the IDE warning.

    Conclusion

    It should be safe as long as you are using the pre-defined constants by Android.