Android中java.lang.StringIndexOutOfBoundsException的完整校对检查

时间:2012-08-08 13:51:32

标签: android null android-asynctask indexoutofboundsexception

if (result.charAt(0) =='Y')下面的代码中仍然出现 java.lang.StringIndexOutOfBoundsException:index = 0 length = 0 错误

还有其他更好的方法来检查if (result == null || result.isEmpty())处的空字符串吗?由于某种原因,未获取空字符串“result”或activity.finish();未执行,并且执行了下一个if语句?请帮忙。

@Override
    protected void onPostExecute(String result) {

        //check if result null or empty
        if (result == null || result.isEmpty()) {

            Toast.makeText(context, "Could Not Check For Updates, Please Try Again. Closing Application.", Toast.LENGTH_LONG).show();
            activity.finish();
        }           
        //update available
        if (result.charAt(0) =='Y') {

            UpdateAlert();
        }
        //no update available
        else if (result.charAt(0) =='N') {

            Toast.makeText(context, "No Updates Available", Toast.LENGTH_SHORT).show();             
        }
        else {

            Toast.makeText(context, "Could Not Check For Updates, Please Try Again. Closing Application : " + result, Toast.LENGTH_LONG).show();
            activity.finish();
        }   

2 个答案:

答案 0 :(得分:0)

尝试在遇到无效结果后从方法返回,如下所述

//check if result null or empty         
           if (result == null || result.isEmpty()) {              
                Toast.makeText(context, "Could Not Check For Updates, Please Try Again. Closing Application.", Toast.LENGTH_LONG).show();             
                activity.finish();         
                return;
           }  

答案 1 :(得分:0)

   if (result == null || result.trim().length()==0) {
         Toast.makeText(context, "Could Not Check For Updates, Please Try Again. Closing  Application.", Toast.LENGTH_LONG).show();
            activity.finish();
        }           
        //update available
        else if (result.charAt(0) =='Y') {
        ^^^^ 
            UpdateAlert();
        }