【问题标题】:if (text.equals("") Crashesif (text.equals("") 崩溃
【发布时间】:2016-02-25 23:05:14
【问题描述】:

我的视图上有一个文本字段,当文本字段上的文本发生更改时,我有一个 if 语句,所以当某个关键字在文本视图中时,一些代码将运行。这是我的 if 语句代码:

 if (text1.equals("rotate")) {


                red.setRotation(red.getRotation() + 5);

                blue.setRotation(blue.getRotation() + 5);


            }

但是当 text1 等于 'rotate' 并运行此代码时,应用程序将崩溃。

这里是日志猫:

【问题讨论】:

标签: java android logging crash


【解决方案1】:

首先你需要初始化text1 对象。从日志可以看出text1对象是null

然后您可以使用以下方法比较字符串:

if (text1 && "rotate".equals(text1.getText().toString()))
{
}

【讨论】:

    【解决方案2】:

    首先:初始化text1

    如果是TextView 那么

    text1 = (TextView) findViewById(R.id.textview_id);
    

    如果是EditText 那么

    text1 = (EditText) findViewById(R.id.editText_id);
    

    第二:这样比较:

    if (text1.getText().toString().equalsIgnoreCase("rotate")) {
       red.setRotation(red.getRotation() + 5);
       blue.setRotation(blue.getRotation() + 5);
     }
    

    【讨论】:

      【解决方案3】:

      看起来 text1 没有初始化。在你的方法中,初始化text1。这是一个示例,说明如何:

      text1   = (EditText)findViewById(R.id.text1);
      

      如果它被初始化并且可以为null,则保护它。

       if ("rotate".equals(text1)) {
      

      【讨论】:

        【解决方案4】:

        原因是 text1 为 null 并且您试图在 null 引用上调用方法。

        要么你忘记初始化它,要么还没有赋值。

        如果您已经进行了初始化并且有机会获得空值,则需要为此设置一个保护条件。

         if (text1 !=null && text1.equals("rotate")) {
        

        这首先检查 null 然后调用方法。

        【讨论】:

        • 简单地做“rotate”.equals(text1) 应该注意 NPE。你不需要检查空值。
        • 同意。 Apache StringUtils.isNotBlank(text1) 怎么样?
        • @StackFlowed 让 OP 学习核心的东西 :) 然后他用它们优化他的代码。
        • 即使我使用此代码,应用程序仍然崩溃。使用相同的日志
        猜你喜欢
        • 1970-01-01
        • 2015-10-04
        • 1970-01-01
        • 2014-08-12
        • 1970-01-01
        • 2018-05-06
        • 1970-01-01
        • 2022-11-02
        • 1970-01-01
        相关资源
        最近更新 更多