【问题标题】:NullPointerException thrown for no reason无缘无故抛出 NullPointerException
【发布时间】:2014-09-26 19:54:40
【问题描述】:

在此代码的第 33 行抛出了一个 NullPointerException

|31|  @Override
|32|  public float[] getVertices() {
|33|    return new float[] {
|34|      center.x - radius, center.y - radius, 0, 1,
|35|      center.x + radius, center.y + radius, 1, 0,
|36|      center.x - radius, center.y + radius, 0, 0,
|37|      center.x - radius, center.y - radius, 0, 1,
|38|      center.x + radius, center.y - radius, 1, 1,
|39|      center.x + radius, center.y + radius, 1, 0
|40|    };
|41|  }

我知道NullPointerExceptions 被抛出的原因有很多,但我只是没有看到该行有任何导致异常的内容。

center.xcenter.yradius 都是之前在代码中定义的,因此它们不为空。我做了一个Log.v(TAG, "center.x: " + center.x + ", center.y: " + center.y + ", radius: " + radius),只是为了检查它们是否已定义,结果如下:center.x: 0, center.y: 0, radius, 1

这是堆栈跟踪:

java.lang.NullPointerException
        at com.vcapra1.breakoutgame.objects.Ball.getVertices(Ball.java:33)
        at com.vcapra1.breakoutgame.objects.TextureObject.<init>(TextureObject.java:17)
        at com.vcapra1.breakoutgame.objects.Ball.<init>(Ball.java:16)
        at com.vcapra1.breakoutgame.BreakoutRenderer.onSurfaceCreated(BreakoutRenderer.java:66)
        at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1509)
        at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1248)

【问题讨论】:

  • 也许中心为空?
  • 请构建一个最小的测试用例。
  • 您在何处/何时登录? - 在创建 float[] 之前尝试记录。
  • @игор - 就在第 33 行之前(当日志在那里时是第 34 行)
  • 为什么这么多人认为记录是要走的路?记录是为了,呃,记录。调试器用于调试。使用调试器,您会在 10 秒内找到它。为什么不用它?

标签: java android nullpointerexception


【解决方案1】:

似乎centerradiusnull。您使用原始类型还是“大”类型?如果使用类,自动装箱也可能会为您提供 NPE。

检查何时设置了这些变量中的任何一个,也许它可以在日志记录之后由同时发生的其他事件/线程设置。尝试同步这两个操作:重置center/radius 并创建一个数组。

【讨论】:

  • center 是一个对象,radius 是原始浮点数
  • 您能解释一下center 的变化吗?
  • 如您所说,该中心似乎正在更改为空。然而,center 被定义为类顶部的成员变量,并且在这个函数内部被访问。如果我在函数顶部重新定义它,它就可以工作。该变量永远不会被访问,那么有什么可以改变这个??
  • 抱歉,不确定,必须看到 :) 尝试使用 setter/getter 并在创建 float[] 之前获取中心实例;然后在修改中心时进行调试......只是说我要做的第一件事;)
  • “从未访问过”是什么意思?如果它从未被访问过,你如何初始化它?显示初始化,而不是声明。
猜你喜欢
  • 2018-06-14
  • 2019-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-07
  • 1970-01-01
  • 2022-08-16
  • 2019-02-19
相关资源
最近更新 更多