【问题标题】:Null Pointer Exception in If else caseIf else 情况下的空指针异常
【发布时间】:2012-12-05 13:32:39
【问题描述】:

我在编辑文本字段上使用 if else case。在这种情况下,如果 Edit text 值大于 5,则当我按下提交按钮时会出现弹出窗口,但是当我没有在 edittext 字段中输入任何值时,程序将强制关闭并给出错误 Null pointer Exception on if case。

下面是我的程序

   EditText name, temp,id_name;
Button submit,display;

ArrayList<NameValuePair> postParameters1 = new ArrayList<NameValuePair>();
String resp=null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    name=(EditText)findViewById(R.id.et_nm);
    temp=(EditText)findViewById(R.id.temp);
    submit = (Button)findViewById(R.id.button1);
    submit.setOnClickListener(this);


}


public void onClick(View butt)
{
    switch(butt.getId())
    {
        case R.id.button1:
            ds.setName(name.getText().toString());

            ds.setTemp(temp.getText().toString()); 

            if( temp > 5)
            {           
                tv1=new TextView(this);
                tv1.setText(" Temp is High");
                Dialog(tv1);
            }
            }

....
....

【问题讨论】:

  • 能否请您澄清您正在谈论的退出文本,else 条件在哪里,还请缩进您的代码以使其更具可读性。
  • difficulties1preg在哪里发布相关代码
  • 什么是DS??请查看 Android 初学者博客。
  • 用你自己的话说........如果EditText 中的文本是null 并且你对这个null 值进行数学计算,如is null less than 5? ,你得到一个NullPointerException
  • 您似乎没有粘贴所有代码,但没有看到其余代码,我猜您忘记了 ELSE 块中的 new TextView(...)

标签: android nullpointerexception


【解决方案1】:

这可能会对您有所帮助。

使用以下代码

更改您的 if
 if( temp.getText() != null && temp.getText().toString().length() > 5)
    {           
         tv1=new TextView(this);
         tv1.setText(" Temp is High");
         Dialog(tv1);
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-12
    相关资源
    最近更新 更多