doubi9615 2012-05-02 13:47
浏览 128

Android:令人难以置信的StringIndexOutOfBoundsException

I send a get request to a php script on webserver that returns 3 lines of text. I handle the response from the server like this:

BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

Than I parse the lines like this:

line = "";
while ((line = rd.readLine()) != null) {
    String a = line.substring(0, line.indexOf('_'));
    String b = line.substring(line.indexOf('_') + 1);
}

And this keeps throwing a StringIndexOutOfBounds exception and I can't really see why. Im already using a similar method elsewhere in my project (with a different PHP script returnig different lines of text and with a different parsing) and it works perfectly fine. When I Log the returned lines to see if they are properly returned from the server, they are the same lines that PHP script sends.

And here is the fun part. When I was growing pretty desperate, I tried to measure the line using:

int l = line.length();

and this returned 11 with my line. Than, when I simply tried to display something using:

line.charAt(5);

it threw a StringIndexOutOfBoundsException: 5. I realy don't know what is wrong with this. Does anyone have an idea? Thanks!

EDIT

This is the PHP script

$query = mysql_query("SELECT * FROM users");
while($row = mysql_fetch_array($query)) {
    print("{$row['id']}
{$row['number']}
");
}

This is my java code:

while ((line = rd.readLine()) != null) {
    Log.v("connection - user list", line); //This line logs: 1_485963
    //But this doesent work
    String a = line.substring(0, line.indexOf('_'));
    String b = line.substring(line.indexOf('_') + 1);
}
  • 写回答

3条回答 默认 最新

  • dpwqicw157673 2012-05-02 13:54
    关注

    Most likely indexOf returns -1 and line.substring(0, -1); throws StringIndexOutOfBoundsException

    EDIT
    Could it be that you might be reading an invisible character/line after 1_485963 line?

    Assume input is like this:

    1_485963
    
    
    

    Then in the log you would see only 1_485963 but the 2nd time loop runs it would crash.

    评论

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探