【问题标题】:Converting Float to String Causing Null Pointer Exception将浮点数转换为字符串导致空指针异常
【发布时间】:2012-05-25 15:48:45
【问题描述】:

我试图在我的布局上的 TextView 中将浮点值“degrees”显示为字符串,但在 tv.setText(mydegrees) 上收到 NullPointerException;我尝试了多种方法将浮点数转换为可用的字符串值,但似乎无法让 TextView 显示浮点值。任何帮助将不胜感激!

注意:度数由 onTouchEvent 操作

来自 XML 的 TextView:

<TextView
android:id="@+id/current_degrees"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical|center"
android:text="@string/app_name"
android:textColor="#FFFF00" />

Java 代码:

float degrees = (float) -65;
String mydegrees = String.format("%.2f", degrees) ;

//...

public void pushClick(View pushClick) {
    switch (pushClick.getId()) {
    case R.id.btn_push:

        TextView tv = (TextView) findViewById(R.id.current_degrees);
        tv.setText(mydegrees);

【问题讨论】:

  • 看起来 tv 是 null 并且与您的学位字符串无关。
  • 你的问题(不管是什么——你没说)与将浮点数转换为字符串无关。
  • 在查看 xml 代码后,我确实发现了导致问题的 TextView 的 id 拼写错误,因为我稍后在相同的布局中使用了类似名称的 TextView 进行测试。修复错字解决了 NPE。
  • 抱歉,布局不同,不一样。

标签: java android floating-point nullpointerexception touch-event


【解决方案1】:
String degreesStr = Float.parseFloat(degrees);

试试这个,它将浮点值转换为字符串。

【讨论】:

    【解决方案2】:

    编辑:正如@Jake King 所说,在我之前的回答中,我没有注意细节(您的mydegree 成员是String 实例。

    这样,您获得NPE 的唯一原因是您的tv TextView 为空。

    请检查您用于活动/渲染器/视图的布局 xml 文件,并确保您有 TextView 或带有 @+id/current_degrees 的任何扩展名。

    此外,您的标题非常具有误导性:如果您的 float 声明和初始化如上所述,那么就不可能有任何 NullPointerException

    【讨论】:

    • 你是对的@Jake King,我错过了。谢谢你的注意,我会改变我的答案。
    【解决方案3】:

    正如 tigrang 所指出的,您的问题不是将浮点数转换为字符串。你所拥有的应该可以正常工作。您的问题是 findViewById() 出于某种原因返回 null 值,大概是因为没有视图具有您提供的 ID。在尝试对其执行任何操作之前,请确保 ID 正确并且您获得了有效的 TextView 实例。

    【讨论】:

    • 如上所述,我在 TextView id 中发现了错字问题,并做出了正确的选择。不知不觉中,我已经在不同的布局中使用了相同的 'current_degrees' id,这就是为什么我能够将 TextView 映射到该 id 而不会出错。
    【解决方案4】:

    简单..使用这个

    tv.setText(degrees+""); //Degrees is the float value
    

    【讨论】:

      猜你喜欢
      • 2011-11-25
      • 2015-09-20
      • 2012-09-06
      • 1970-01-01
      • 1970-01-01
      • 2013-01-11
      • 1970-01-01
      • 1970-01-01
      • 2014-04-02
      相关资源
      最近更新 更多