简体   繁体   中英

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.

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM