I'm getting a NullPointerException after an initial method in the constructor of the class is called. That method initializeJdbc() is suppose to fill the field "titles" with names of titles from the Course table in the database. However, I keep getting that exception. Does anyone know what I'm doing wrong? Here is the code below:
@Named(value = "courseName")
@ApplicationScoped
public class CourseNameJSfBean {
private PreparedStatement studentStatement = null;
private String choice;
private String[] titles;
public CourseNameJSfBean() {
initializeJdbc();
}
private void initializeJdbc() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
System.out.println("Driver loaded");
Connection connection = DriverManager.getConnection(
"jdbc:mysql://localhost/javabook", "root", "12345");
PreparedStatement statement = connection.prepareStatement(
"select title from Course");
ResultSet result = statement.executeQuery();
ArrayList<String> list = new ArrayList<>();
while (result.next()) {
list.add(result.getString(1));
}
titles = new String[list.size()];
list.toArray(titles);
studentStatement = connection.prepareStatement(
"select Student.ssn, Student.firstName, Student.mi, " +
"Student.lastName, Student.phone, Student.birthDate, Student.street, " +
"Student.zipCode, Student.deptId from Student, Enrollement, Course " +
"where Course.title = ? and Student.ssn = Enrollment.ssn and " +
"Enrollment.courseId = Course.courseId");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
// Getters & setters
public ResultSet getStudents() throws SQLException {
if (choice == null) {
if (titles.length == 0)
return null;
else
studentStatement.setString(1, titles[0]);
} else {
studentStatement.setString(1, choice);
}
return studentStatement.executeQuery();
}
The NullPointerException comes up at the line that says
if (titles.length == 0)
Here's the exception message:
Caused by: java.lang.NullPointerException
at CourseNameJSfBean.getStudents(CourseNameJSfBean.java:71)
at org.jboss.weld.proxies.CourseNameJSfBean$Proxy$_$$_WeldClientProxy.getStudents(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at javax.el.BeanELResolver.getValue(BeanELResolver.java:363)
... 56 more