Menelaos Kotsollaris
Menelaos Kotsollaris

Reputation: 5506

Null Pointer Exception while trying creating a general object - Android

I have this simple general class where it should give me the width and the height of the running device : deviceInfo.c

public class deviceInfo
{
private float width;
private float height;
private Context cx;

public deviceInfo(Context context)
{
    this.width = getDeviceWidth();
    this.height = getDeviceHeight();
    this.cx=context;
}

public int getDeviceHeight()
{
    WindowManager wm = (WindowManager) cx.getSystemService(Context.WINDOW_SERVICE);
    Display display = wm.getDefaultDisplay();
    return display.getHeight();
}

public int getDeviceWidth()
{
    WindowManager wm = (WindowManager) cx.getSystemService(Context.WINDOW_SERVICE);
    Display display = wm.getDefaultDisplay();
    return display.getWidth();
}
}

When i try to create an object in my activity i get a Null pointer exception. Why is that? As I am guessing my problem is on Context parameter, but I have no clue how to fix that. Thanks in advance.

Upvotes: 0

Views: 701

Answers (2)

Viacheslav
Viacheslav

Reputation: 5593

You are accessing cx variable before it initialized so it causes NullPointerException. Rework to

this.cx=context;
this.width = getDeviceWidth();
this.height = getDeviceHeight();

Upvotes: 2

BatScream
BatScream

Reputation: 19700

Change the initialization order of cx to:

public deviceInfo(Context context)
{
    this.cx=context;
    this.width = getDeviceWidth();
    this.height = getDeviceHeight();

}

The Nullpointer could be in the lines containing the code:

WindowManager wm = (WindowManager) cx.getSystemService(Context.WINDOW_SERVICE);

where, cx will be obviously null, since these functions are called before the initialization of cx in your code.

Upvotes: 2

Related Questions