在分页时获取OutOfBoundsException

时间:2014-09-07 10:44:27

标签: android string pagination indexoutofboundsexception

我正在为android创建一个epub阅读器。对于分页部分,我试图获取整个字符串内容,然后在字符串中搜索空格。然后我得到文本高度并将其与屏幕高度进行比较。如果仍然(文本高度<屏幕高度)我循环遍历字符串并在while循环中执行相同的操作。

一切顺利,但当谈到字符串的结尾时,我得到了IndexOutOfBoundsException。我附上了Logcat的屏幕截图。

enter image description here

我用来获取页面的代码就是这样的

public String getNoOfPages(String text){


    String remainingString = "";

    try{
        int screenHeight = getScreenHeight();
        String originalText = text;
        String strToModify = text;


        StringBuilder newString = new StringBuilder();
        StringBuilder oldString = new StringBuilder();


        int startIndex = 0;
        String strToFind = " ";
        int index = strToModify.indexOf(strToFind,startIndex);

        newString.append(originalText.substring(startIndex, index+1));
        oldString.append(newString.toString());
        startIndex = index+1;

        int textHeight = getTextHeight(newString.toString());

        while(textHeight < screenHeight){
            index = strToModify.indexOf(strToFind,startIndex);
            oldString.replace(0,oldString.toString().length(),newString.toString());
            newString.append(originalText.substring(startIndex, index+1));
            startIndex = index+1;
            textHeight = getTextHeight(newString.toString());
        }

        remainingString = originalText.substring(oldString.length()-1,originalText.length());

    }catch(Exception e){
        Log.d("chathura123","Error in getNoOfPages  " );
        e.printStackTrace();

    }

    return remainingString; 
}

逻辑是当剩余的字符串是空字符串(“”)时,这意味着它是页面内容的结尾。所以我想检查,直到它返回一个空字符串。

上面的方法在另一个while循环中调用。 (在异步任务中)     String tmp = null;

        try{
             tmp = reader.getNoOfPages(content);

             while (!tmp.equals("")) {

                 tmp = reader.getNoOfPages(tmp);
                 page_count++;

                 if(page_count==80){
                     Log.d("chathura123", "80 th iteration");
                 }

                 Log.d("chathura123", "inside while "+page_count);
             }

        }catch(Exception e){
            Log.d("chathura123", "error occured in getPageCount");
        }

这有什么问题?为什么我得到OutOfBoundsException?

谢谢。

1 个答案:

答案 0 :(得分:1)

可能位于最后一行,如果没有字符,则originalText.substring(startIndex, index+1)会出现错误,如果originalText没有index+1长度/索引。