[android] How to get screen width and height

I tried to use following code to get screen width and height in android app development:

Display display = getWindowManager().getDefaultDisplay(); 
int screenWidth = display.getWidth();
int screenHeight = display.getHeight();

but I got NullPointerException for my display, why? how to get screen width and height then?

The answer is


Within an activity, you can call:

int width = this.getResources().getDisplayMetrics().widthPixels;
int height = this.getResources().getDisplayMetrics().heightPixels;

When you're in a View, then you need to get the Context first:

int width = getContext().getResources().getDisplayMetrics().widthPixels;
int height = getContext().getResources().getDisplayMetrics().heightPixels;

This will work in all Android version, available since API 1, and never deprecated.


       /*
        *DisplayMetrics: A structure describing general information about a display, such as its size, density, and font scaling.
        * */

 DisplayMetrics metrics = getResources().getDisplayMetrics();

       int DeviceTotalWidth = metrics.widthPixels;
       int DeviceTotalHeight = metrics.heightPixels;

WindowManager w = getWindowManager();
Display d = w.getDefaultDisplay();
DisplayMetrics metrics = new DisplayMetrics();
d.getMetrics(metrics);

Log.d("WIDTH: ", String.valueOf(d.getWidth()));
Log.d("HEIGHT: ", String.valueOf(d.getHeight()));

From service:

Display  display= ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int width = display.getWidth(); 
int height = display.getHeight(); 

Try with the following code to get width and height of screen

int widthOfscreen =0;
int heightOfScreen = 0;
DisplayMetrics dm = new DisplayMetrics();
        try {
            ((Activity) context).getWindowManager().getDefaultDisplay()
                    .getMetrics(dm);
        } catch (Exception ex) {
        }
         widthOfscreen  = dm.widthPixels;
heightOfScreen  = dm.heightPixels;

If you're calling this outside of an Activity, you'll need to pass the context in (or get it through some other call). Then use that to get your display metrics:

DisplayMetrics metrics = context.getResources().getDisplayMetrics();
int width = metrics.widthPixels;
int height = metrics.heightPixels;

UPDATE: With API level 17+, you can use getRealSize:

Point displaySize = new Point();
activity.getWindowManager().getDefaultDisplay().getRealSize(displaySize);

If you want the available window size, you can use getDecorView to calculate the available area by subtracting the decor view size from the real display size:

Point displaySize = new Point();
activity.getWindowManager().getDefaultDisplay().getRealSize(displaySize);

Rect windowSize = new Rect();
ctivity.getWindow().getDecorView().getWindowVisibleDisplayFrame(windowSize);

int width = displaySize.x - Math.abs(windowSize.width());
int height = displaySize.y - Math.abs(windowSize.height());
return new Point(width, height);

getRealMetrics may also work (requires API level 17+), but I haven't tried it yet:

DisplayMetrics metrics = new DisplayMetrics();
activity.GetWindowManager().getDefaultDisplay().getRealMetrics(metrics);

This is what finally worked for me:

DisplayMetrics metrics = this.getResources().getDisplayMetrics();
int width = metrics.widthPixels;
int height = metrics.heightPixels;

Alternative way using function

private int[] getScreenSIze(){
        DisplayMetrics displaymetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
        int h = displaymetrics.heightPixels;
        int w = displaymetrics.widthPixels;

        int[] size={w,h};
        return size;

    }

on button click or on your create function add the following code

int[] screenSize= getScreenSIze();
        int width=screenSize[0];
        int height=screenSize[1];
        screenSizes.setText("Phone Screen sizes \n\n  width = "+width+" \n Height = "+height);

See demo source code


Display display = getActivity().getWindowManager().getDefaultDisplay(); 
int screenWidth = display.getWidth();
int screenHeight = display.getHeight();
Log.d("Tag", "Getting Width >> " + screenWidth);
Log.d("Tag", "Getting Height >> " + screenHeight);

This worked properly in my application


if (Build.VERSION.SDK_INT >= 11) {
        Point size = new Point();
        try {
            this.getWindowManager().getDefaultDisplay().getRealSize(size);
            screenWidth = size.x;
            screenHeight = size.y;
        } catch (NoSuchMethodError e) {
             screenHeight = this.getWindowManager().getDefaultDisplay().getHeight();
             screenWidth=this.getWindowManager().getDefaultDisplay().getWidth();
        }

    } else {
        DisplayMetrics metrics = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(metrics);
        screenWidth = metrics.widthPixels;
        screenHeight = metrics.heightPixels;
    }

Try via context.getResources().getDisplayMetrics() if you have a context available.


below answer support api level below and above 10

 if (Build.VERSION.SDK_INT >= 11) {
            Point size = new Point();
            try {
                this.getWindowManager().getDefaultDisplay().getRealSize(size);
                screenWidth = size.x;
                screenHeight = size.y;
            } catch (NoSuchMethodError e) {
                 screenHeight = this.getWindowManager().getDefaultDisplay().getHeight();
                 screenWidth=this.getWindowManager().getDefaultDisplay().getWidth();
            }

        } else {
            DisplayMetrics metrics = new DisplayMetrics();
            this.getWindowManager().getDefaultDisplay().getMetrics(metrics);
            screenWidth = metrics.widthPixels;
            screenHeight = metrics.heightPixels;
        }

    int scrWidth  = getWindowManager().getDefaultDisplay().getWidth();
    int scrHeight = getWindowManager().getDefaultDisplay().getHeight();

DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);

int height = metrics.heightPixels;
int width = metrics.widthPixels;

i guess the code which you wrote is deprecated.


Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to android-layout

How to check if a key exists in Json Object and get its value How to center the elements in ConstraintLayout Android - how to make a scrollable constraintlayout? Add ripple effect to my button with button background color? This view is not constrained vertically. At runtime it will jump to the left unless you add a vertical constraint Is it possible to put a ConstraintLayout inside a ScrollView? Differences between ConstraintLayout and RelativeLayout How to remove title bar from the android activity? How to have EditText with border in Android Lollipop Android: ScrollView vs NestedScrollView

Examples related to android-emulator

flutter run: No connected devices How to remove the Flutter debug banner? Android Studio AVD - Emulator: Process finished with exit code 1 Android Studio Emulator and "Process finished with exit code 0" Run react-native on android emulator ERROR Android emulator gets killed Error while waiting for device: Time out after 300seconds waiting for emulator to come online Unfortunately Launcher3 has stopped working error in android studio? updating Google play services in Emulator Android Studio emulator does not come with Play Store for API 23

Examples related to android-activity

Kotlin Android start new Activity The activity must be exported or contain an intent-filter How to define dimens.xml for every different screen size in android? Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which? Not an enclosing class error Android Studio java.lang.IllegalStateException: Fragment not attached to Activity Soft keyboard open and close listener in an activity in Android android.app.Application cannot be cast to android.app.Activity Android Shared preferences for creating one time activity (example) Android ListView with onClick items

Examples related to android-widget

How to create custom button in Android using XML Styles How can I do factory reset using adb in android? Setting Action Bar title and subtitle Determine when a ViewPager changes pages Android Image View Pinch Zooming Add padding on view programmatically Changing position of the Dialog on screen android Using setImageDrawable dynamically to set image in an ImageView how to get html content from a webview? Android How to adjust layout in Full Screen Mode when softkeyboard is visible