Search code examples
javajdbcnullpointerexceptionojdbc

Getting java.lang.NullPointerException when while(rs.next()) is encountered second time


String[] Starttime= new String[5000];
String[] Endtime = new String[5000];

int st=0;
int et=0;

while(rs.next()) {           
    ResultSet rs_second=stmt.executeQuery("*Select Query*");

    while (rs_second.next()) {
        if(condition){
            rs_second.previous();
            Endtime[et]=rs_second.getString("rec_datetime");
            rs_second.next();
            et=et+1;
        }
        else if(condition){
            Starttime[st]=rs_second.getString("rec_datetime");
            st=st+1;
        }
    }
    System.out.println();
    System.out.println(st);
    System.out.println(et);

    for(int i=0;i<st;i++) {
        Date Start=new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse(Starttime[i]);
        Date End=new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse(Endtime[i]);
        long diff = End.getTime() - Start.getTime();
        long diffSeconds = diff / 1000 % 60;
        long diffMinutes = diff / (60 * 1000) % 60;
        long diffHours = diff / (60 * 60 * 1000) % 24;
        long diffDays = diff / (24 * 60 * 60 * 1000);

        System.out.println(diffDays+" Days "+diffHours +" Hours "+diffMinutes+" Minutes "+diffSeconds+" Seconds");
    }
} 

When the above code is executed, at first the code runs absolutely fine, but when accessing rs.next() again. its showing:

java.lang.NullPointerException
    at oracle.jdbc.driver.ScrollableResultSet.next(ScrollableResultSet.java:344)
    at triage.Triage.main(Triage.java:84)

I tried to execute rs.next() separately, and it contains 17 records. Tried with everything but not able to debug the exception.

This question is not a duplicate of What is a nullpointerexception and how do I fix it In this case I cannot debug why it's coming, since the code is running absolutely fine once and when while(rs.next()) is encountered second time, null pointer exception is caused.


Solution

  • You haven't included how you get the first resultset. If you get the error there maybe you should?

    My guess is that you use the same statement to get the second result set and since in java you can't have more than one open result set per statement when you go in the while loop for the first time you reuse the statement and close the first result set.

    The Statement API says:

    By default, only one ResultSet object per Statement object can be open at the same time. Therefore, if the reading of one ResultSet object is interleaved with the reading of another, each must have been generated by different Statement objects. All execution methods in the Statement interface implicitly close a statment's current ResultSet object if an open one exists.

    So try to create a new statement object in the while loop and use that one