Why is it the last data is always null - java

I have a problem getting all the data in jtable. The last data that display is always "null" even though i enter data in that cell. Can anyone help me
for (int i = 0; i < model_1.getRowCount(); i++) {
if (String.valueOf(model_1.getValueAt(i, 0)) != null && !String.valueOf(model_1.getValueAt(i, 0)).isEmpty()) {
date = String.valueOf(model_1.getValueAt(i, 0));
}
if (String.valueOf(model_1.getValueAt(i, 1)) != null && !String.valueOf(model_1.getValueAt(i, 1)).isEmpty()) {
meal = String.valueOf(model_1.getValueAt(i, 1));
}
if (String.valueOf(model_1.getValueAt(i, 2)) != null && !String.valueOf(model_1.getValueAt(i, 2)).isEmpty()) {
time = String.valueOf(model_1.getValueAt(i, 2));
}
if (String.valueOf(model_1.getValueAt(i, 3)) != null && !String.valueOf(model_1.getValueAt(i, 3)).isEmpty()) {
activity = String.valueOf(model_1.getValueAt(i, 3));
}
try {
System.out.println(date + " " + meal + " " + time + " " + activity);
}
}
here is my sample output:
2017-10-02 sdfsd 01:30 sdfsdfsf
2017-10-03 dsfdfs 01:00 null

I guess your jtable is still active so the data hasn't been saved to the model yet.
Try to add this before your code:
if (table.isEditing())
table.getCellEditor().stopCellEditing();

Related

Sonar null pointer voilation while reading excel file

Sonar giving null pointer violation for below line of code.
cell1.getRow()
Please could you help us to resolve this issue.
private List<InvalidUploadedExcelData> validateSheet(Sheet sheet) throws Exception {
InvalidUploadedExcelData ITD;
ArrayList<InvalidUploadedExcelData> returnedInvalidTestDataList = new ArrayList<InvalidUploadedExcelData>();
Cell cell1, cell2, cell3;
for (int i = 1; i < sheet.getRows(); i++) {
cell1 = sheet.getCell(0, i);
cell2 = sheet.getCell(1, i);
cell3 = sheet.getCell(2, i);
if ((cell1 == null || StringUtils.isEmpty(cell1.getContents().trim()))) {
ITD = new InvalidUploadedExcelData(TITLE_TEST_ID, "Row-" + (cell1.getRow() + 1) + " Column-" + (cell1.getColumn() + 1) + " is missing");
returnedInvalidTestDataList.add(ITD);
} else if (!isValidProperty(cell1.getContents().trim())) {
ITD = new InvalidUploadedExcelData(TITLE_TEST_ID + ":" + cell1.getContents().trim(), "Row-" + (cell1.getRow() + 1) + " Column-" + (cell1.getColumn() + 1) + " is not valid");
returnedInvalidTestDataList.add(ITD);
}
}
return returnedInvalidTestDataList;
}
The following lines will cause a NullPointerException if cell1 is actually null as you check for null in the if-condition, but you still enter the branch and then access cell1.getRow() in there.
if ((cell1 == null || StringUtils.isEmpty(cell1.getContents().trim()))) {
ITD = new InvalidUploadedExcelData(TITLE_TEST_ID, "Row-" + (cell1.getRow() + 1) + " Column-" + (cell1.getColumn() + 1) + " is missing");
You will need to get the row/column information differently in this case to be safe.

Restrictions OR in hibernate (Java)

I want rewrite sql query to hibernate criteria and I have this problem.
It is original:
if (null != filterGroupIds && !filterGroupIds.isEmpty()) {
hqueryText += (requereAnd ? " and " : "") + "(";
requereAnd = true;
if (filterGroupIds.contains("null")) {
hqueryText += " w.crmUser.groupId = null ";
filterGroupIds.remove("null");
hqueryText += filterGroupIds.isEmpty() ? "" : "or";
}
if (!filterGroupIds.isEmpty())
hqueryText += " w.crmUser.groupId in (" + StringUtils.join(filterGroupIds.iterator(), ",") + ")";
hqueryText += ")";
}
It is my criteria:
if (null != filterGroupIds && !filterGroupIds.isEmpty()) {
if (filterGroupIds.contains(Integer.valueOf(-1))) {
criteria.add(Restrictions.eq("crmUser.groupId", null));
filterGroupIds.remove(Integer.valueOf(-1));
if (!filterGroupIds.isEmpty()) {
criteria.add(Restrictions.or(Restrictions.in("crmUser.groupId", filterGroupIds)));
}
}else {
criteria.add(Restrictions.in("crmUser.groupId", filterGroupIds));
}
}
but my OR Restrictions not work.
You should be getting compile time error for
criteria.add(Restrictions.or(Restrictions.in("crmUser.groupId", filterGroupIds)));
as Restrictions.or() takes two criterion values.Recheck your code and pass two criterion object to be compared.

Why is my jpql .getResultList() returning 0 rows for a good query

I was using the exact same query yesterday and it was working fine today I made a few changes to flow of the program and the query no longer returns and rows.
the first function that my programs goes to:
public void prepareSummary(Date startDate , Date endDate)
{
int getStartDay = getDayFromDate(startDate);
int getStartMonth = getMonthFromDate(startDate);
//
int getEndDay = getDayFromDate(endDate);
int getEndMonth = getMonthFromDate(endDate);
int getYear = getYearFromDate(startDate);
if(getStartMonth <= getEndMonth)
{
if(getStartMonth == getEndMonth)
{
if(getStartDay < getEndDay)
{
while(getStartDay <= getEndDay)
{
Calendar cal = Calendar.getInstance();
cal.set( getYear, getStartMonth, getStartDay);
Date queryStart = getStartOfDay(cal.getTime());
Date queryEnd = getEndOfDay(cal.getTime());
List<Object[]> res = getSumList(queryStart, queryEnd);
doQuery(res);
++getStartDay;
}
}
else
{
}
}
else
{
}
}
else
{
}
}
Here is what getSumList looks like:
public List<Object[]> getSumList(Date start, Date end) {
String query = "";
query += "SELECT COUNT(s) pCount,"
+ "p.nameText,"
+ "g.nameText,"
+ "t.shiftID"
+ " FROM Sheets s , GradeNames g , SpecieNames p, ShiftTimes t"
+ " WHERE s.createdLocal > :start and s.createdLocal < :end"
+ " AND s.specieNameIndex = p.nameIndex "
+ " AND s.gradeNameIndex = g.nameIndex"
+ " AND s.shiftIndex = t.shiftIndex"
+ " GROUP BY p.nameText , g.nameText , t.shiftID";
Query q = em.createQuery(query);
q.setParameter("start", start);
q.setParameter("end", end);
return q.getResultList();
}
This next function doesn't matter at this point because nothing is being executed because the list length is zero:
private void doQuery(List<Object[]> obj)
{
int length = obj.size();
String grade = null;
Long standingCount = (long) 0;
System.out.println("Length" + length);
for (int i = 0; i < length; ++i) {
// HAVE A LIST OF ALL ITEMS PULLED FROM DATABASE
Object[] tmpObj = obj.get(i);
Long tmpCount = (Long) tmpObj[0];
String tmpSpecieName = (String) tmpObj[1];
Double tmpThickness = Double.parseDouble(getSpecie().getThicknessFromSpecie(tmpSpecieName));
String tmpLength = getSpecie().getLengthFromSpecie(tmpSpecieName);
String tmpGradeName = (String) tmpObj[2];
String tmpShift = (String) tmpObj[3];
tmpSpecieName = getSpecie().getSpecieFromSpecie(tmpSpecieName);
//// END OF ALL ITEMS PULLED FROM DATABASE
if (grade != pullGradeName(tmpGradeName) && grade != null) {
System.out.println("Count:" + standingCount + "Grade:" + tmpGradeName + "--" + "Specie" + tmpSpecieName + "Shift:" + tmpShift + "Thickness:" + tmpThickness + "Length:" + tmpLength + "SpecieNAme:" + tmpSpecieName);
// do previous insert
grade = pullGradeName(tmpGradeName);
} else if (grade != pullGradeName(tmpGradeName) && grade == null) {
grade = pullGradeName(tmpGradeName);
} else if (grade == pullGradeName(tmpGradeName)) {
standingCount = standingCount + tmpCount;
}
System.out.println("Count:" + tmpCount + "Grade:" + tmpGradeName + "--" + "Specie" + tmpSpecieName + "Shift:" + tmpShift + "Thickness:" + tmpThickness + "Length:" + tmpLength + "SpecieNAme:" + tmpSpecieName);
}
}
Check the SQL that is generated, and the tables you are querying over. As the query requires inner joins, if one of the tables was cleared, it would return no results. If you want to get a 0 count, you need to use an outer join syntax which isn't possible in JPA unless you use object level mappings:
"SELECT COUNT(s) pCount,"
+ "p.nameText,"
+ "g.nameText,"
+ "t.shiftID"
+ " FROM Sheets s outer join s.specialNameIndex p,"
+ " outer join s.gradeNameIndex g, outer join s.shiftIndex t"
+ " WHERE s.createdLocal > :start and s.createdLocal < :end"
+ " GROUP BY p.nameText , g.nameText , t.shiftID";

Handling SQL Null Parameters Elegantly

I'm generating an SQL statement by checking if each of the column fields submitted to the query are empty (== null) or not. It seems that my approach is pretty naive so I'm wondering what can be done about handling null parameters elegantly. When something isn't specified it should simply match anything.
Here is the code:
public List<Flight> findMatchingFlights(Flight flight)
{
List<Flight> foundFlights = new ArrayList<>();
StringBuilder sqlQueryBuilder = new StringBuilder();
sqlQueryBuilder.append("SELECT * FROM Flights");
boolean emptyQuery = true;
if(flight.getDeparture() != null)
{
if(emptyQuery)
{
sqlQueryBuilder.append(" WHERE ");
emptyQuery = false;
}
sqlQueryBuilder.append("Departure = '" + flight.getDeparture() + "'");
}
if(flight.getArrival() != null)
{
if(emptyQuery)
{
sqlQueryBuilder.append(" WHERE ");
emptyQuery = false;
}
else
{
sqlQueryBuilder.append(" AND ");
}
sqlQueryBuilder.append("Arrival = '" + flight.getArrival() + "'");
}
if(flight.getFlightNumber() != null)
{
if(emptyQuery)
{
sqlQueryBuilder.append(" WHERE ");
emptyQuery = false;
}
else
{
sqlQueryBuilder.append(" AND ");
}
sqlQueryBuilder.append("Number = '" + flight.getFlightNumber() + "'");
}
if(flight.getFlightMinutes() != 0)
{
if(emptyQuery)
{
sqlQueryBuilder.append(" WHERE ");
emptyQuery = false;
}
else
{
sqlQueryBuilder.append(" AND ");
}
sqlQueryBuilder.append("Duration = " + flight.getFlightMinutes());
}
/*
...
A bunch more fields
*/
if(flight.getAirplane() != null)
{
if(emptyQuery)
{
sqlQueryBuilder.append(" WHERE ");
}
else
{
sqlQueryBuilder.append(" AND ");
}
sqlQueryBuilder.append("Airplane = '" + flight.getAirplane() + "'");
}
sqlQueryBuilder.append(";");
// Execute sql and fill list with rows that match
}
You can create the common method for the below block and call the method by passing the arguments.
if(flight.getArrival() != null)
{
if(emptyQuery)
{
sqlQueryBuilder.append(" WHERE ");
emptyQuery = false;
}
else
{
sqlQueryBuilder.append(" AND ");
}
sqlQueryBuilder.append("Arrival = '" + flight.getArrival() + "'");
}
Best approach would be to do the trick in SQL than checking for null in Java. This is how you can do it.
sqlQueryBuilder.append("(Number = '" + flight.getFlightNumber() + "' OR " + flight.getFlightNumber() + " IS NULL)");
This way you wont have to check null in java, if the flight.getFlightNumber() is null then this where clause will always return true which is what you would want.
The only drawback to this method is that the clause will be included in the query, but since you are intending to use these columns to query the table incase they are not null, i would assume the table would be indexed likewise.
sqlQueryBuilder.append("SELECT * FROM Flights WHERE 1 = 1");
then you don't need emptyQuery flag and checks and many if else constractions.
List<Flight> foundFlights = new ArrayList<>();
StringBuilder sqlQueryBuilder = new StringBuilder();
sqlQueryBuilder.append("SELECT * FROM Flights WHERE 1 = 1");
if(flight.getDeparture() != null) {
sqlQueryBuilder.append("AND Departure = '" + flight.getDeparture() + "'");
}

Regarding if else multiple conditions

I have a constants file abcder.constants as shown below
public static final String ABC_abbject_EOD = "DDD_Report";
public static final String CDE_abbject_INTRADAY = "FFD_Report";
Now I have the below method as shown below
public void Gen(String[] toAddress, String[] ccAddress, String abbject,
String message, String defIdentifier, Date date)
Now in this method there can be two cases that is either defIdentifier is null or abbject parameter has a value
So if defIdentifier is null then abbject has a value which is coming from a abcderconstant so in that case I have to do something. That is depending upon the value of the abject it can be ABC_abbject_EOD or CDE_abbject_INTRADAY
If defIdentifier is not null then abbject is null then in that case I have to perform some other thing
So, I have developed the code as shown below please advise is this correct way
if (defIdentifier != null && abbject== null)
{
String s = defIdentifier + "-" + formatter.format(now.getTime()) + "." + "doc";
}
if (defIdentifier == null && abbject.equalsIgnoreCase(abcderconstants.ABC_abbject_EOD))
{
String s = "DDD-Report" + "-" + formatter.format(now.getTime()) + "." + "doc";
}
if (defIdentifier == null && abbject.equalsIgnoreCase(abcderconstants.CDE_abbject_INTRADAY))
{
String s = "FFD-Report" + "-" + formatter.format(now.getTime()) + "." + "doc";
}
StringBuilder sb = new StringBuilder();
if (defIdentifier != null && abbject == null) {
sb.append(defIdentifier);
} else if (defIdentifier == null && abbject != null ) {
if(abbject.equalsIgnoreCase(abcderconstants.ABC_abbject_EOD)) {
sb.append("DDD-Report");
} else if (abbject.equalsIgnoreCase(abcderconstants.CDE_abbject_INTRADAY)) {
sb.append("FFD-Report");
} else {
// throw invalid abbject type exception?
}
} else {
// both defIdentifier and abbject are either null or not null. Illegal args?
}
sb.append("-" + formatter.format(now.getTime()) + "." + "doc");
String s = sb.toString();
Put String s = ... outside the if statements. It may be a good idea to check if abbject is null. Please try to use better variable names.
String s = null;
if (defIdentifier != null && abbject == null) {
s = defIdentifier + "-" + formatter.format(now.getTime()) + "." + "doc";
}
else if (defIdentifier == null && abbject != null && abbject.equalsIgnoreCase(abcderconstants.ABC_abbject_EOD)) {
s = "DDD-Report" + "-" + formatter.format(now.getTime()) + "." + "doc";
}
else if (defIdentifier == null && abbject != null && abbject.equalsIgnoreCase(abcderconstants.CDE_abbject_INTRADAY)) {
s = "FFD-Report" + "-" + formatter.format(now.getTime()) + "." + "doc";
}

Categories

Resources