Reputation: 82543
I have a while loop that adds elements read using a Buffered Reader to an ArrayList. The loop works fine, except after it finishes, the app doesn't seem to move on. The relevant code is:
int ctr = 1;
while((test = bf.readLine()) != null)
{
Log.i(TAG, test);
users.add(test);
Log.i(TAG, "" + (ctr++));
}
Log.i(TAG, "Loop done.");
The two log statements in the loop execute 4 times each, which is normal behavior. However, the statement after the loop doesn't execute. It's like it gets stuck. I'm pretty sure it doesn't go into the loop either, as the two log statements inside don't execute anymore either.
bf is the BufferedReader, users is the ArrayList.
LogCat Output:
08-04 01:35:37.472: I/UM(2937): UserInfo{0:Primary:3}
08-04 01:35:37.472: I/UM(2937): 1
08-04 01:35:37.476: I/UM(2937): UserInfo{1:Test1:0}
08-04 01:35:37.476: I/UM(2937): 2
08-04 01:35:37.476: I/UM(2937): UserInfo{2:test2:0}
08-04 01:35:37.480: I/UM(2937): 3
08-04 01:35:37.480: I/UM(2937): UserInfo{3:testxyz:0}
08-04 01:35:37.480: I/UM(2937): 4
Does anybody have any idea what my (probably stupid) mistake is?
Upvotes: 0
Views: 185
Reputation: 9323
I expect it's the condition:
while((test = bf.readLine()) != null)
Think of it this way:
Console ("line1\nline2\n")
----> BufferedReader ("line1\n", "line2\n")
----> bf.readline() ("line1\n")
----> bf.readline() ("line2\n")
Your condition is checking for when Console closes its connection entirely, at which point BufferedReader will notice and return null
.
What's actually happening is that Console's connection to BufferedReader is still open. BufferedReader is waiting for another \n
to get passed in from the Console before readLine()
will return "line3\n".
Upvotes: 2
Reputation: 5661
your code is blocking on the line :
while((test = bf.readLine()) != null)
And it is doing so because the stream supplying data to bf
is never being closed.
(This answer is not mine, its just a quick summary from the comments.)
Upvotes: 3