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);
}
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.
First try to debug. OR else try this
I am pretty sure that line.indexOf('_') is not available in given string
1) first print log of the string and check '_' character is available.
try this to avoid StringIndexOutOfBoundsException
while ((line = rd.readLine()) != null) {
if (line.indexOf('_') != -1) {
String a = line.substring(0, line.indexOf('_'));
String b = line.substring(line.indexOf('_') + 1);
}else{
// means that index is not found
}
}
And finally you told string len = 11 and when printing char at position 5 is throw error.
check what u r doing in between printing len of the string and printing char at postion 5.
FINALLY some times you might get junk character from the buffer input stream. becoz its passing from n/w. check that also.
Maybe I'm getting old and blind but how does this
print("{$row['id']}
{$row['number']}
");
produce
1_485963
Surely
print("{$row['id']}_{$row['number']}
");
is what you need. Apologies if that is not valid PHP as the syntax of that has always refused to stick in my brain.