java.lang.NullPointerException ERROR - java

I'm getting this null error on this line but I'm doing an if check and setting an empty string if null. Am I doing this wrong?
java.lang.NullPointerException
at form.setSam((teamBean.getHead().getNone().getCode() == null) ? "" : teamBean.getHead().getNone().getSamCode().toString()); //SAM
Code:
public int show(Action action) throws Exception
{
HttpServletRequest request = action.getRequest();
String[] params;
if (!isEmpty(params[0]))
{
String teamNumber= params[0];
TeamBean teamBean = DAO.getTeamDAO().getTeamByNumber(Long.parseLong(teamNumber));
Fake form = new fakeForm();
form.setMoor(teamBean.getHeader().getMoor());
form.setDoor(Double.toString(teamBean .getDoors()));
form.setURC(Double.toString(teamBean.getURCS()));
form.setUMC(Double.toString(teamBean.getUMCSt()));
form.setWeek(Long.toString(teamBean.getHead().getWeek().getnow())); //WEEK
ERROR HERE -->> form.setSam((teamBean.getHead().getNone().getCode() == null) ? "" : teamBean.getHead().getNone().getSamCode().toString()); //SAM

For clarity, this is the expression that gives you the NullPointerException:
teamBean.getHead().getNone().getCode()
You aren't checking if getNone returns null.

You get it because teamBean.getHead().getNone() is null. And since you're calling getCode() on this null value, you get a NullPointerException.
Note that
form.setSam((teamBean.getHead().getNone().getCode() == null) ? "" : "");
could be rewritten as
form.setSac("");
(except you wouldn't have the NullPointerException)

Related

Operators in a table

There are 7 rows of output for table, how can I modify this so row 6 displays either of the three providers.
I tried something like this :
template.getProvider2() != null || template.getProvider3() != null ||
template.getProvider1() != null ?
template.getProvider2().getBusinessUnit(): "" ||
template.getProvider3().getBusinessUnit(): "" ||
template.getProvider3().getBusinessUnit(): "",
which gives me an error of StringBuilder not accepting the OR operator,
I'd appreciate any help on this.
Thanks
Here is my code:
public GetEmailTemplatesResponse getEmailTemplates() throws Exception {
StringBuilder stringBuilder = new StringBuilder();
String tableRow = "<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>";
Map<String, EmailTemplate> templates = templateRedisCacheReader.getTemplatesByCacheType(CacheType.EMAIL_TEMPLATE);
templates.values()
.forEach(template -> stringBuilder.append(String.format(tableRow,
template.getTemplateId(),
template.getProvider1() != null ? template.getProvider1().getId() : "",
template.getProvider2() != null ? template.getProvider2().getId() : "",
template.getProvider3() != null ? template.getProvider3().getId() : "",
template.getEnv(),
template.getProvider2() != null ? template.getProvider2().getBusinessUnit(): "", // <--
template.getPriority()))
);
I tried to check if all the providers are null and if one of them is not null , then display bussiness unit for that provider
There's a function commonly used in SQL that returns the first non-null parameter called "coalesce". You could write a Java equivalent of that.
Object coalesce(Object... objects) {
for (Object obj : objects) {
if(obj != null) return obj;
}
return null;
}
...
Provider firstNonNullTemplate=(Provider) coalesce(template.getProvider1(), template.getProvider2(), template.getProvider3());

Nullcheck of status at line 114 of value previously dereferenced in Sonar

For the below piece of code Sonar throws me a critical violation - Correctness - Nullcheck of status value previously dereferenced
Can someone suggest on this on what am I doing wrong here?
code
public boolean isExactMacthBill(AddressResponse response) {
boolean exactMatch = false;
if (null != response && null != response.getHostResponse()) {
HostResponseDetail hostResponse = response.getHostResponse();
String addressStatus = hostResponse.getMatchStatus();
ResponseDetail status = hostResponse.getStatus();
String addressMatchCode = status.getCode();
if (null != response.getMatchedAddresses() && response.getMatchedAddresses().size() > 0 && status != null) {
if (addressStatus.equalsIgnoreCase(Constants.USPS_MATCH)
|| (addressStatus.equalsIgnoreCase(Constants.PARTIAL_MATCH)
&& addressMatchCode.equalsIgnoreCase("3SXU"))) {
exactMatch = true;
} else
exactMatch = false;
}
}
return exactMatch;
}
The actual problem is in the line after the highlighted one - you've got:
if (... && status != null)
Just remove that check and I think SonarLint will be happy. It unnecessary, because if status is null then status.getCode() will already have thrown an exception before you reach that condition.
Fundamentally, you need to know whether getStatus() should ever return null - whether you have to handle that situation explicitly. If you do, you should check it before your call to status.getCode(), and react accordingly. If you don't, it's fine to call the getCode() method - if your assumption is incorrect, you'll get a NullPointerException as normal, which is probably the most appropriate result for the scenario of "the world isn't as I expect it to be". But you shouldn't try to "handle" it being null after you've already depended on it being non-null.
status can be null when it is received from hostResponse.getStatus();; so when the line String addressMatchCode = status.getCode(); is called it can result in a Null Reference Exception.
You should verify all the variables if there are null before calling methods on them.
Move your addressMatchCode inside your if condition which null check the status.
public boolean isExactMacthBill(AddressResponse response) {
boolean exactMatch = false;
if (null != response && null != response.getHostResponse()) {
HostResponseDetail hostResponse = response.getHostResponse();
String addressStatus = hostResponse.getMatchStatus();
ResponseDetail status = hostResponse.getStatus();
if (null != response.getMatchedAddresses() && response.getMatchedAddresses().size() > 0 && status != null) {
String addressMatchCode = status.getCode();
if (addressStatus.equalsIgnoreCase(Constants.USPS_MATCH)
|| (addressStatus.equalsIgnoreCase(Constants.PARTIAL_MATCH)
&& addressMatchCode.equalsIgnoreCase("3SXU"))) {
exactMatch = true;
} else
exactMatch = false;
}
}
return exactMatch;
}

Why the value of this string is still null although I have checked if it is null?

This is my code:
String invite = LogInUtil.getInvite(this);
System.out.println(invite.equals(null));
if ( invite != null){
System.out.println(invite);
System.out.println("=============================================="+(invite != null));
Invitation.setInvite(Long.valueOf(invite));
}
This is the method in LoginUtil:
public static String getInvite(Context mContext){
// 获取搜索记录文件内容
SharedPreferences sp = mContext.getSharedPreferences(PREFERENCE_NAME, 0);
String history = sp.getString(PREFERENCE_NAME, "");
String[] tmpHistory = history.split("==");
if (tmpHistory.length==2){
return tmpHistory[1];
}
return null;
}
This is the result in logcat:
I/System.out: false
I/System.out: null
I/System.out: ==============================================true
Is there anything wrong with my code? Maybe is a stupid question. I'm a fresher,and I need your help. TTThanks!
It might be case you are getting "null" as string value rather than null, try below code, if still not work try to clean your project
String invite = LogInUtil.getInvite(this);
if ( invite != null && !"null".equals(invite)){
System.out.println(invite);
System.out.println("=============================================="+(invite != null));
Invitation.setInvite(Long.valueOf(invite));
}
The error is at this line invite.equals(null). Your are checking null.equals(null) that's why it throws NULLPointerException.
Please correct it to the System.out.println(invite == null); so it will not throw exception.
Corrected Sample code
String invite = LogInUtil.getInvite(this);
System.out.println(invite == null);
if ( invite != null){
System.out.println(invite);
System.out.println("=============================================="+(invite != null));
Invitation.setInvite(Long.valueOf(invite));
}
Use StringUtils.empty() method for checking null and empty in case of string.
I think u are getting "null" string in ur invite variable.

How to remove Cyclomatic complexcity

I am getting Cyclomatic complexity (The Cyclomatic Complexity of this method "mapRow" is 13 which is greater than 10 authorized) from below code :
public RedemptionReport mapRow(ResultSet rs, int row) throws SQLException {
RedemptionReport redemptionReport = new RedemptionReport();
redemptionReport.setRedeemDate(rs.getString(1));
redemptionReport.setCashierID(rs.getString(2) != null? rs.getString(2) : "");
redemptionReport.setTillNo(rs.getString(3) != null? rs.getString(3) : "");
redemptionReport.setReferenceNumber(rs.getString(4) != null? rs.getString(4) : "");
redemptionReport.setTransactionNumber(rs.getString(5) != null? rs.getString(5) : "");
redemptionReport.setRedemptionAmount(rs.getString(6) != null? rs.getString(6) : "0");
redemptionReport.setNetBillValues(rs.getString(7) != null? rs.getString(7) : "0");
redemptionReport.setStoreCode(rs.getString(8) != null? rs.getString(8) : "");
redemptionReport.setCardNumber(rs.getString(9) != null? rs.getString(9) : "");
redemptionReport.setCardType(rs.getString(10) != null? rs.getString(10) : "");
redemptionReport.setStoreDesc(rs.getString(11) != null? rs.getString(11) : "");
redemptionReport.setZoneDesc(rs.getString(12) != null? rs.getString(12) : "");
redemptionReport.setMobileNo(rs.getString(13) != null? rs.getString(13) : "");
redemptionReport.setSchemeName(rs.getString(14));
return redemptionReport;
}
How to remove this complexity from the above code?
Create a method that will encapsulate the ternary operator, e.g.:
private String get(String val, String def) {
return val != null ? val : def
}
Or even simpler:
private String get(String val) {
return val != null ? val : ""
}
override RedemptionReport's setters. This should belong to domain class as the default values makes sense only in RedemptionReport class.
Pass "rs.getString(x)" value to the setter method.
public RedemptionReport mapRow(ResultSet rs) throws SQLException {
RedemptionReport redemptionReport = new RedemptionReport();
redemptionReport.setRedeemDate(this.getResultFromResultSet(rs.getString(1)));
redemptionReport.setCashierID(this.getResultFromResultSet(rs.getString(2)));
redemptionReport.setTillNo(this.getResultFromResultSet(rs.getString(3)));
redemptionReport.setReferenceNumber(this.getResultFromResultSet(rs.getString(4)));
redemptionReport.setTransactionNumber(this.getResultFromResultSet(rs.getString(5)));
redemptionReport.setRedemptionAmount(this.getResultFromResultSet(rs.getString(6)));
redemptionReport.setNetBillValues(this.getResultFromResultSet(rs.getString(7)));
redemptionReport.setStoreCode(this.getResultFromResultSet(rs.getString(8)));
redemptionReport.setCardNumber(this.getResultFromResultSet(rs.getString(9)));
redemptionReport.setCardType(this.getResultFromResultSet(rs.getString(10)));
redemptionReport.setStoreDesc(this.getResultFromResultSet(rs.getString(11)));
redemptionReport.setZoneDesc(this.getResultFromResultSet(rs.getString(12)));
redemptionReport.setMobileNo(this.getResultFromResultSet(rs.getString(13)));
redemptionReport.setSchemeName(this.getResultFromResultSet(rs.getString(14)));
return redemptionReport;
}
define another private message to do such work(Null Check and return default value).
private String getResultFromResultSet(String val){
return val != null ? val : "";
}

Why does this statement not work appropriately? Ternary operation & classcastexception

I have a JSONObject which I am parsing and sometimes some of the data is null.
In this case, ReportId = null..so, I tried to use a ternary operator to prevent the ClassCastException, however, it doesn't work.
The specific object throwing the error has "ReportId":null....can I not do this?
Line:
item.setReportId((jsonObj.get("ReportId") != null || jsonObj.get("ReportId") != "null") ? (Integer)jsonObj.get("ReportId") : 0);
I just had a look at the documentation for JSONObject, it appears to have a number of convenience methods. For example:
item.setReportId( (!jsonObj.isNull("ReportId")) ? jsonObj.getInt("ReportId") : 0);
Try with following condition,
If there is valid numeric reportid in json then set the report id otherwise set 0 as report id
try{
reportId = (jsonObj.get("ReportId") != null) ? Integer.parseInt((String)jsonObj.get("ReportId")) : 0;
}catch(Exception ex){
reportId = 0;
}
item.setReportId(reportId);

Categories