Anson Yao
Anson Yao

Reputation: 1584

How does the readLine() has a nullpointer exception?

I am confused about the readLine() of the BufferedReader class. I have the following code:

BufferedReader ir=new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
StringBuffer sb=new StringBuffer();

while(ir.readLine()!=null){
      String tmp=ir.readLine();
      sb.append(tmp);
      if(tmp!=null){
      Log.i("recHtml", tmp);
      }

The code works as expected. However, if we remove the

        if(tmp!=null){

Then the code will get a nullpointerexception for the

        Log.i("recHtml", tmp);

I am quite confused. I already check this in the while statement, why there is a still a nullpointer error?

Upvotes: 0

Views: 298

Answers (4)

user2885596
user2885596

Reputation: 69

yeah exactly you are reading twice by using the readLine() twice in while loop. First time it read form the 1st readLine in the while loop and again if the control enters the while loop body then with the 2nd readLine() it read the string as null. That is the reason why it is giving null pointer Exception.

Try using readLine() once in the while loop.

Upvotes: 0

nachokk
nachokk

Reputation: 14413

You are reading 2 lines in one cycle.

Change your code to something like this.

String tmp= null;
while( (tmp = ir.readLine()) !=null){
      sb.append(tmp);
      Log.i("recHtml", tmp);
}

Upvotes: 1

CodingIntrigue
CodingIntrigue

Reputation: 78525

You're reading the line twice. The second time, you could potentially hit the end of the file and receive a null value. Introduce your tmp variable outside of the while loop so that you only read it once each time:

String tmp = null;
while((tmp = ir.readLine()) !=null){
    sb.append(tmp);
    Log.i("recHtml", tmp);
}

Upvotes: 1

Fritz
Fritz

Reputation: 10045

while(ir.readLine()!=null){
    //...
}

This already reads a line, so when you want to actually obtain the line you checked about you get the next one, instead. In the last case, that's null since there are no other lines left.

The check should actually be done with the hasNextLine method, defined for that check:

while(ir.hasNextLine()){
    //...
}

Upvotes: 7

Related Questions