2012-04-04 44 views
-4

发明Android和Java的人并没有为自己发明。自从我开始在Android中开发Java应用程序之后,我得到了最荒谬的错误,而且我真的很疯狂(如果我这样做了,Google和Sun Microsystems将会制作“booooom”)尝试获取字符串长度时,Android应用程序崩溃

我有这个简单的代码,获取作为参数传递的字符串的长度。该应用程序崩溃,使我花了几分钟发誓和折磨键盘。

我的代码:

@Override 
protected void onPostExecute(String result) { 
    if (result.length() == 0) { 
     txtStatus.setText("Ready"); 
    } 
} 

如果我删除它的工作状态(文字“就绪”显示在我的TextView)。这是奇怪的,我知道我可能会错过一些小东西。

给我一些线索,谢谢你的一切!

P.S.如果你听到从邻居那里传来一声枪响,那可能就是我。

+0

保存自己很多的压力,并了解logcat的实用工具 - 可以通过Eclipse或通过命令行。当某些事情崩溃时,logcat输出将包含一个堆栈跟踪,其中有一些有用的提示,例如空指针异常。在最糟糕的情况下,将异常消息复制/粘贴到Google搜索中,以查找其他已经看到相同问题并从已经解决问题的其他人的智慧中获益的人。 – Colin 2012-04-05 03:05:21

回答

4

因为你的字符串可能是null。像这样做:

@Override 
protected void onPostExecute(String result) { 
    if (!TextUtils.isEmpty(result)) { 
     txtStatus.setText("Ready"); 
    } 
} 
+0

是啊!我将结果初始化为空,但我认为在从网页获取空白内容后它会变成空字符串。无论如何,你的答案是我的解决方案。谢谢! – ali 2012-04-04 19:52:46

1

试试这个:

@Override 
protected void onPostExecute(String result) { 
    if (result != null && result.length() == 0) { 
     txtStatus.setText("Ready"); 
    } 
} 
0

检查结果为空第一,妥善处理这个问题,然后检查它的长度。我最好的猜测是你有一个未处理的NullPointerException。

@Override 
protected void onPostExecute(String result) { 
    if (result == null) { 
     result = ""; // change this line if null is an error. 
    } 
    if (result.length() == 0) { 
     txtStatus.setText("Ready"); 
    } 
} 

一个调试技巧,找出什么是错误的,并使您的程序崩溃将包装条件在try/catch块。

@Override 
protected void onPostExecute(String result) { 
    try { 
     if (result.length() == 0) { 
      txtStatus.setText("Ready"); 
     } 
    catch (Throwable t) { // both error and exception inherit from Throwable. 
     // print or inspect 't' here to determine the reason for the crash. 
    } 
} 
0

正如Waqas所说,问题是因为您的字符串可能为空。如果字符串为null方法长度不defined.So添加一个附加条件检查空即

if(result ==NULL) 
// do something else 
else 
//your code here 
相关问题