55

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?

kablu
  • 629
  • 1
  • 7
  • 26
Leem
  • 17,220
  • 36
  • 109
  • 159

14 Answers14

133

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);
areyling
  • 2,181
  • 2
  • 20
  • 25
  • 1
    Good answer. Please add the possibility to use getResources() without context. – Kostanos Jun 26 '13 at 06:37
  • 1
    @Kostanos As [getResources()](http://developer.android.com/reference/android/content/Context.html#getResources()) is a an abstract method on the Context class, you can't use it without a Context. If you're in an Activity you can just call `getResources()`; if you're in a view, you can use `getContext().getResources()`. If neither of these work for you and you don't want to pass in a Context, see [this StackOverflow question](http://stackoverflow.com/questions/16277011/getresources-from-static-method-without-context) for an alternative solution. Hope that helps! – areyling Jun 26 '13 at 16:20
  • You are right, it worked on the AndEngine Activities classes, but probably won't work on the default Activity class from SDK. Thanks. – Kostanos Jun 26 '13 at 16:23
  • @Kostanos It will work for any Activity, but only because Activity extends Context. – Ilya Kogan May 08 '14 at 15:26
  • 1
    This is the answer, not sure why @Leem will not accept this or atleast one of the answers.. – SARose Mar 16 '15 at 14:35
  • `height ` seems higher than the visible screen,how to get the real height of the screen. – zionpi Jul 31 '15 at 06:54
  • @zionpi see update for an alternative way to get the available area. – areyling Jul 31 '15 at 16:36
  • if context doesn't exists, use `getApplicationContext()` instead. – computingfreak Dec 05 '16 at 06:14
  • Don't use `getWindowManager().getDefaultDisplay()`, you cannot guarantee if you are the current display. The original answer was more correct than the edited one. – EpicPandaForce Dec 29 '20 at 09:01
41

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.

EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
Khulja Sim Sim
  • 3,469
  • 1
  • 29
  • 28
  • getApplicationContext() is used to get the context from Fragment, not from View. From view it would be getContext() instead. – Oliver Hausler Mar 29 '15 at 01:15
  • @OliverHausler getContext will work too, only if you're in a view. getApplicationContext will work both in view and fragment, and in an activity too. It basically gives you the context of overall application, what's more important is to get the context first before calling resources to get pixel size. Please provide a strong reason for down-voting if you have any. – Khulja Sim Sim Mar 31 '15 at 22:08
  • I have not down-voted anything, I have only commented that what you have stated is incorrect, and it is. "When you're in a View, then you need to get the Context first" -> `int width = getApplicationContext().getResources().getDisplayMetrics().widthPixels;` does not work from within a view. – Oliver Hausler Mar 31 '15 at 23:11
  • It should, it does. Try correctly, like all other up-voters did. – Khulja Sim Sim Apr 01 '15 at 00:00
  • 1
    Check the reference http://developer.android.com/reference/android/view/View.html#getContext() and/or try it. There is no getApplicationContext() method in view. – Oliver Hausler Apr 01 '15 at 00:18
19

From service:

Display  display= ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int width = display.getWidth(); 
int height = display.getHeight(); 
XXX
  • 8,996
  • 7
  • 44
  • 53
Maidul
  • 1,289
  • 16
  • 30
15

This is what finally worked for me:

DisplayMetrics metrics = this.getResources().getDisplayMetrics();
int width = metrics.widthPixels;
int height = metrics.heightPixels;
Arnold Spence
  • 21,942
  • 7
  • 74
  • 67
fritz
  • 151
  • 1
  • 2
13

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

Arnold Spence
  • 21,942
  • 7
  • 74
  • 67
MrJre
  • 7,082
  • 7
  • 53
  • 66
7
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.

Housefly
  • 4,324
  • 11
  • 43
  • 70
4
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;
    }
Sujith S Manjavana
  • 1,417
  • 6
  • 33
  • 60
3

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;
Sunil Kumar Sahoo
  • 53,011
  • 55
  • 178
  • 243
2
       /*
        *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;
IntelliJ Amiya
  • 74,896
  • 15
  • 165
  • 198
2
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()));
Mark
  • 520
  • 1
  • 7
  • 21
DallinDyer
  • 1,378
  • 13
  • 14
1
    int scrWidth  = getWindowManager().getDefaultDisplay().getWidth();
    int scrHeight = getWindowManager().getDefaultDisplay().getHeight();
Axxel
  • 21
  • 2
  • 1
    Hi, your post has been flagged as "low quality", probably because it consists solely of code. You could massively improve your answer by providing an explanation of exactly how and why this answers the question? – Ben Sep 29 '13 at 19:09
  • it returns width and height in pixels or not – Zar E Ahmer Apr 16 '15 at 07:43
0
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

Rudolf Coutinho
  • 215
  • 3
  • 11
0

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);
blackgreen
  • 34,072
  • 23
  • 111
  • 129
Daniel Nyamasyo
  • 2,152
  • 1
  • 24
  • 23
0

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;
        }
Rahul
  • 3,293
  • 2
  • 31
  • 43