java - 尝试创建一般对象时出现空指针异常 - Android

标签 java android properties nullpointerexception android-studio

我有一个简单的通用类,它应该为我提供正在运行的设备的宽度和高度: 设备信息.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();
}
}

当我尝试在 Activity 中创建对象时,出现空指针异常。这是为什么?我猜测我的问题出在 Context 参数上,但我不知道如何解决这个问题。 提前致谢。

最佳答案

将cx的初始化顺序更改为:

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

}

空指针可能位于包含代码的行中:

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

其中,cx 显然为 null,因为这些函数是在代码中初始化 cx 之前调用的。

关于java - 尝试创建一般对象时出现空指针异常 - Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25666669/

相关文章:

java - 为什么会出现此 "String to object of type <objecttype>"错误,如何解决

使用 XMLEncoder 时出现 java.lang.Instantiation 异常

java - 如何为单列连接覆盖 @JoinColumn 中默认生成的 SQL 名称

android - 使用 MediaMuxer 混合相机预览 h264 编码的基本流

Android Studio : App crashes after adding Firebase

java - 按后退按钮时强制关闭

java - 无法覆盖 toString 方法

java - 将配置文件转换为 HTML

c# - 尝试访问派生类中基类属性的 protected 访问器时出错

java - 公共(public)配置 - JNDIConfiguration - 如何?