I need advice on how I can avoid java.lang.NullPointerException
when dealing with JDBC
result set which I put on Swing
components such as JTable
I have written a method which gets the result set encapsulated in an object from a DAO Implementation which I populate inside a DefaultTableModel
.
The problems is, the object returned by the dao implementation service may or may not have data/result set if the database table has no record yet.
This results to a NullPointerException
public DefaultTableModel getMiscellaneous(int gradeLevelId){
DefaultTableModel defaultTableModel = new DefaultTableModel();
String[] columns = {"Name","Amount"};
MiscellaneousFees miscellaneousFees = schoolFeesDaoImpl.getMiscellaneous(gradeLevelId);
List<Fee> feeList = miscellaneousFees.getFees();
for(Fee fee: feeList){
Object[] rowData = {fee.getName(),fee.getAmount()};
defaultTableModel.addRow(rowData);
}
defaultTableModel.setColumnIdentifiers(columns);
return defaultTableModel;
}
public MiscellaneousFees getMiscellaneous(int gradeLevelId) {
MiscellaneousFees miscellaneousFees = new MiscellaneousFees();
List<Fee> feeList = new ArrayList<>();
String SQL = "{CALL getMiscellaneousFeesByGradeLevelId(?)}";
try (Connection con = DBUtil.getConnection(DBType.MYSQL);
CallableStatement cs = con.prepareCall(SQL);){
cs.setInt(1, gradeLevelId);
try(ResultSet rs = cs.executeQuery();){
while(rs.next()){
SchoolYear schoolYear = new SchoolYear();
schoolYear.setSchoolYearId(rs.getInt("schoolyear_id"));
schoolYear.setYearFrom(rs.getInt("yearFrom"));
schoolYear.setYearTo(rs.getInt("yearTo"));
schoolYear.setIsActive(rs.getBoolean("isActive"));
schoolYear.setStart_date(rs.getDate("start_date"));
schoolYear.setEnd_date(rs.getDate("end_date"));
schoolYear.setIsCurrentSchoolYear(rs.getBoolean("isCurrentSchoolYear"));
GradeLevel gradeLevel = new GradeLevel();
gradeLevel.setId(rs.getInt("gradelevel_id"));
gradeLevel.setLevel(rs.getInt("grade_level"));
gradeLevel.setIsActive(rs.getBoolean("isActive"));
FeeCategory feeCategory = new FeeCategory();
feeCategory.setCategory(rs.getString("fee_category"));
feeCategory.setId(rs.getInt("fee_category_id"));
Fee fee = new Fee();
fee.setId(rs.getInt("fee_id"));
fee.setName(rs.getString("fee_name"));
fee.setDescription(rs.getString("fee_description"));
fee.setAmount(rs.getDouble("fee_amount"));
fee.setFeeCategory(feeCategory);
fee.setGradeLevel(gradeLevel);
fee.setSchoolYear(schoolYear);
feeList.add(fee);
}
miscellaneousFees.setFees(feeList);
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(null,e.getMessage());
}
return miscellaneousFees;
}
Any suggestion or advice of how I can prevent the NullPointerException
when result set contained in the miscellaneous
object is empty?
I get the NullPointerException
error in this line of code
MiscellaneousFees miscellaneousFees = schoolFeesDaoImpl.getMiscellaneous(gradeLevelId);
Thank you.