Jannat Jannat - 3 months ago 9
Java Question

How can I remove "java.lang.NullPointerException"?

I am trying to write data from the ATTENDANCE table into the AttendanceData.csv file but it is showing the following

NullPointerException
. Can anyone tell me that how can i get rid of this exception?

Exception in thread "main" java.lang.NullPointerException
at ReadCol.data(ReadCol.java:43)
at ReadCol.main(ReadCol.java:71)


Here is my code

public class ReadCol {
public String[] array;
public BufferedWriter out;
public void data() throws Exception{
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn= DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","System","mine");
conn.setAutoCommit(false);
Statement st=conn.createStatement();
ResultSet rs=st.executeQuery("select * from ATTENDANCE");
ResultSetMetaData rsmd = rs.getMetaData();
System.out.println("No of columns in the table:"+ rsmd.getColumnCount());
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
String fname = rsmd.getColumnName(i);
System.out.println("COLUMN NAME: " + fname);
}
System.out.println();
while(rs.next()){
File file = new File("E:\\eclipse\\workspace\\AutoAttendanceSystem\\res\\AttendanceData.csv");
List<String> lines = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);
for (String line : lines) {
array = line.split(",");
if( ( rs.getString(1) == null && array[0] == null || rs.getString(1) != null && rs.getString(1).equals(array[0]) ) && ( rs.getString(7) == null && array[6] == null|| rs.getString(7) != null && rs.getString(7).equals(array[6]) )){
JOptionPane.showMessageDialog(null, "Can't Update Because record already exist");
}
else{
out.write(rs.getString("ATTENDANT_NAME") + ", "); //line 43
out.write(rs.getString("ATTENDANT_AGE") + ", ");
out.write(rs.getString("ATTENDANT_CONTACT_NO") + ", ");
out.write(rs.getString("ATTENDANT_DEPARTMENT_NAME") + ", ");
out.write(rs.getString("REGISTRATION_NUM") + ", ");
out.write(rs.getString("ABSENT_PRESENT") + ", ");
out.write(rs.getString("ATTENDANCE_TIME_DATE") + ", ");
out.newLine();
out.flush();
System.out.println("updated, not already Exist");
JOptionPane.showMessageDialog(null, "Updated");
}
}
System.out.println(array[0]);
}

out.close();
conn.close();
}catch (IOException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception{
ReadCol r = new ReadCol();
r.data(); //line 71
}
}

Answer

The BufferedWriter out is unassigned, i.e. is null. Then out.write(...) gives a null pointer exception.