Hick
Hick

Reputation: 36404

Class cast exception while using WindowManager in Android

My code to get the screen height dynamically:

Display display = ((Activity) getContext()).getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    int width = size.x;
    int height = size.y;

Error: Error: java.lang.ClassCastException: android.app.Application Complete log cat: http://pastebin.com/8zUNFUYn

Edit: Changed code to this:

Display display =  (activity).getWindowManager().getDefaultDisplay();

        Point size = new Point();
        display.getSize(size);
        int width = size.x;
        int height = size.y;

Worked but, gave a new error that is display.getSize(size) is not a method. Is that API depreceated?

Upvotes: 1

Views: 406

Answers (2)

Blackbelt
Blackbelt

Reputation: 157447

Context

is base class for both Application and Activity. Since your a getting an Application with getContext(), casting it to Activity causes the ClassCastExecption.

Upvotes: 2

Android Killer
Android Killer

Reputation: 18489

replace your line with this :

if you are using this code inside activity then use this:

Display display = this.getContext().getWindowManager().getDefaultDisplay();

Upvotes: 1

Related Questions