Java parsing a string into an int, then a null - java

Got this code:
System.out.println("Introduce salary: ");
Scanner alpha8 = new Scanner(System.in);
String salary = alpha8.nextLine();
int salaryNew = 0;
if(salary .isEmpty()){
salary = null;
}else{
salaryNew = Integer.parseInt(salary);
}
How can i make this to output only 1 variable from the IF? Because if the introduced value is null (blank space from scanner, like enter) sets salary to null wich i use later on.
The thing is that i either need a "null" or an "int value".
In the "else" i cannot do this:
salary = Integer.parseInt(salary);
because id get an error, neither i can parse int into to null.
And this methodto convert dates:
public static Date changeDate(String introducedDate) throws ParseException {
SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
java.util.Date sqlDate = sdf.parse(introducedDate);
java.sql.Date newSqlDate= new java.sql.Date(sqlDate.getTime());
return newSqlDate;
}
If introducedDate is null it will throw an exception, how can i change that method to return NULL if introduced date is NULL too?

Part 1
The thing is that i either need a "null" or an "int value".
If you want to have an integer value which is nullable, use the wrapper class Integer:
Integer salaryNew = null;
if (!salary.isEmpty()) {
salaryNew = Integer.parseInt(salary);
}
Part 2
If introducedDate is null it will throw an exception, how can i change that method to return NULL if introduced date is NULL too?
You need to check the value of the parameter before you do any work on it (See #nem's answer, since he beat me to that half).

Check out #azurefrog's answer for your first question.
If introducedDate is null it will throw an exception, how can i change that method to return NULL if introduced date is NULL too?
public static Date changeDate(String introducedDate) throws ParseException {
if(introducedDate == null) { // ADD THIS CHECK
return null;
}
SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
java.util.Date sqlDate = sdf.parse(introducedDate);
java.sql.Date newSqlDate= new java.sql.Date(sqlDate.getTime());
return newSqlDate;
}

you can do -
if(salary != null && ! salary.isEmpty() )
{
return Integer.parseInt(salary);
}else{
return null;
}
for your second part add this if condition before doing any date format-
if(introducedDate == null) {
return null;
}

Related

Sonar: Possible null pointer dereference due to return value of called method

I am getting issue from Sonar: "Style - Possible null pointer dereference due to return value of called method. findbugs:NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE.
the issue is on lockUntil.after(new Date());
try {
String sql = "select lock_until from shedlock where NAME=?";
Timestamp lockUntil = jdbcTemplate.queryForObject(sql, new Object[] {taskname}, Timestamp.class);
return lockUntil.after(new Date()); //issue line
} catch (EmptyResultDataAccessException e){
LOGGER.info("Checking shedlock for locked task[" + taskname + "]. No task exists. Exception: " + e.getLocalizedMessage());
return false;
}
I've tried to change this issue line with
Date date = new Date();
return lockUntil.after(date);
or
Date date = new Date();
if(date != null)
return lockUntil.after(date);
else
return false; -> this line is dead end
But it introduces other issues.
Can anyone please guide?
Assuming that new Date() will never return null should be a valid assumption. My guess is that the possibly null value Sonar is complaining about is lockUntil. I assume that queryForObject will return null if the query does not match any rows, so it makes sense that you'd get a complaint about using lockUntil without first checking if it is null.

Correct way to initialize wrapper Integer

I have a drop down field in application which displays numbers.
When user doesn't select any value from drop down, I would want to insert as null to database.
How can I initialize an Integer wrapper class to null?
I have tried as
Integer days = new Integer(null);
if (request.getParameter("days").equals("")) {
} else {
days =
Integer.parseInt(request.getParameter("days"));
}
However I am getting the following error, so what is the correct method in declaring Integer variable?
NumberFormatException at test.doPost(Controller.java:23);
How to initialize an Integer variable so that if no values are selected by user then null should get inserted.
You should initialize with null:
Integer days = null;
if (request.getParameter("days") != null && !request.getParameter("days").isEmpty()) {
days = Integer.parseInt(request.getParameter("days"));
}
UPDATE: Better to validate its an integer first:
Integer days = null;
if(request.getParameter("days")!=null && request.getParameter("days").matches("^\\d+$"))
{
days = Integer.parseInt(request.getParameter("days"));
}
UPDATE 2: To be able to insert null in DB:
if (project.getDays() != null)
callablestatement.setInt(2, project.getDays());
else
callablestatement.setNull(2, java.sql.Types.INTEGER);
What about setting the days object to null and then checking to see if the days object is null or is empty:
Integer days = null;
if (request.getParameter("days") != null && !request.getParameter("days").isEmpty()) {
// rest of code.
Apart from the declaration on which others have commented.
You are getting NumberFormatException because request.getParameter("days") is returning a non integer value text or null. parseInt method throws NumberFormatException when it gets a string input which is not a valid integer value.
You cannot trust the value of the days parameter in the request.
What if some client will pass an invalid value? (a non-number string).
For this reason you should catch NumberFormatException when you try to parse the parameter value.
Integer days = null;
String parameterValue = request.getParameter("days");
if (parameterValue != null && !parameterValue.isEmpty()) {
try {
days = Integer.parseInt(parameterValue);
} catch (NumberFormatException e) {
// log or something
}
}
With a try/catch:
Integer days = null;
try {
days = Integer.parseInt(request.getParameter("days"));
} catch (final NumberFormatException ex) {
// ignore
}
or with guava Ints
Integer days = null;
final String param = request.getParameter("days");
if (param != null) {
days = Ints.tryParse(param);
}
This way, you avoid the NumberFormatException if "days" is not parsable.
How about :
Integer days = null;
String param = request.getParameter("days");
if (param != null && !"".equals(param)) {
days = Integer.parseInt(request.getParameter("days"));
}

java.lang.NullPointerException Error with login

As i want to "log in" I always get the
org.apache.jasper.JasperException: java.lang.NullPointerException Error
I get that it occurs when you want to access a reference type that has not been initialized but I just can't get the hang of it in my mind.
Uksekaart kaart = null;
boolean allowed = false;
java.util.Date dt = new java.util.Date();
out.println(dt);
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
if(request.getParameter("kaardi_id")!=null && request.getParameter("ukse_nr")!=null){
kaart = kh.kysiUksekaart(Integer.parseInt(request.getParameter("kaardi_id")));
String[] ukseList = kaart.getUksed().split(" ");
for(int i=0; i<ukseList.length;i++){
if(Integer.parseInt(ukseList[i]) == Integer.parseInt(request.getParameter("ukse_nr"))){
allowed = true;
}
}
for(veeb.AjutineLuba k:kh.kysiAjutisedLoad()){
if(k.getKaardi_ID() == Integer.parseInt(request.getParameter("kaardi_id")) && k.getUkse_nr() == Integer.parseInt(request.getParameter("ukse_nr"))){
if(dt.getTime() > df.parse(k.getAlgus()).getTime() && dt.getTime() < df.parse(k.getLopp()).getTime()){
allowed = true;
}
}
}
}
Netbeans shows line 72
String[] ukseList = kaart.getUksed().split(" ");
Check if kaart is not null else there is a problem with your getUksed() method.
You getting NULL in line:
kaart = kh.kysiUksekaart(Integer.parseInt(request.getParameter("kaardi_id")));
Result of this line kaart = null, and when program tries to do kaart.getUksed() it can not find getUksed() method for object that is equal NULL.
I dont know architecture of all APP but try this:
String[] ukseList = new Array();
if (kaart != null) {
ukseList = kaart.getUksed().split(" ");
}
Otherwise you need figured out why kh.kysiUksekaart(Integer.parseInt(request.getParameter("kaardi_id"))) gives null.

Why this SimpleDateFormat lost info about time?

I have this Java method that process a ResultSet.
protected void populateDto(String[] rowSet, ResultSet rs, String[] columunsNames) throws SQLException {
for (int i = 0; i < rowSet.length; i++) {
rowSet[i] = rs.getString(columunsNames[i]);
}
}
As you can see all result are treated as String type (getString is used whatever is the column type). When a Date column is encountered it is automatically converted into a String. The resulting date will appear similar to this one:
2012-08-01 16:10:47.0
I have modified the above script, creating something like that:
protected void populateDto(String[] rowSet, ResultSet rs, String[] columunsNames) throws SQLException {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
for (int i = 0; i < rowSet.length; i++) {
Object o = rs.getObject(columunsNames[i]);
if (o instanceof Date) {
rowSet[i] = formatter.format((Date)o);
} else {
rowSet[i] = (String)o;
}
}
}
This method treat everything as Object, after, will check if that Object is an instance of Date. If this is true it will formatted in according to the formatter. The problem is that in this way the data returned is like:
2012-08-01 00:00:00.0
Why?
Update 1 - Last working method implementation:
protected void populateDto(String[] rowSet, ResultSet rs, String[] columunsNames, SimpleDateFormat formatter) throws SQLException {
Timestamp ts = null;
for (int i = 0; i < rowSet.length; i++) {
Object obj = rs.getObject(columunsNames[i]);
if (obj instanceof Date) {
ts = rs.getTimestamp(columunsNames[i]);
rowSet[i] = formatter.format(ts);
} else {
if(obj!=null)
rowSet[i] = obj+"";
else
rowSet[i] = "";
}
}
}
java.sql.Date does not store info about time:
To conform with the definition of SQL DATE, the millisecond values wrapped by a java.sql.Date instance must be 'normalized' by setting the hours, minutes, seconds, and milliseconds to zero in the particular time zone with which the instance is associated.
This method treat everything as Object, after, will check if that Object is an instance of Date.
Instead of date use java.sql.Timestamp, with this you can get Date as well as Time either you persist data or fetch data.
Update 1
You can have a general method like
public Timestamp getTimestamp(int columnIndex) throws SQLException {
Object value = getObject(columnIndex);
if (value instanceof Timestamp) return (Timestamp) value;
}
this will return the date and time and you could call by passing the column index.

Android Json and null values

How can I detect when a json value is null?
for example: [{"username":null},{"username":"null"}]
The first case represents an unexisting username and the second a user named "null". But if you try to retrieve them both values result in the string "null"
JSONObject json = new JSONObject("{\"hello\":null}");
json.put("bye", JSONObject.NULL);
Log.e("LOG", json.toString());
Log.e("LOG", "hello="+json.getString("hello") + " is null? "
+ (json.getString("hello") == null));
Log.e("LOG", "bye="+json.getString("bye") + " is null? "
+ (json.getString("bye") == null));
The log output is
{"hello":"null","bye":null}
hello=null is null? false
bye=null is null? false
Try with json.isNull( "field-name" ).
Reference: http://developer.android.com/reference/org/json/JSONObject.html#isNull%28java.lang.String%29
Because JSONObject#getString returns a value if the given key exists, it is not null by definition. This is the reason JSONObject.NULL exists: to represent a null JSON value.
json.getString("hello").equals(JSONObject.NULL); // should be false
json.getString("bye").equals(JSONObject.NULL); // should be true
For android it will raise an JSONException if no such mapping exists. So you can't call this method directly.
json.getString("bye")
if you data can be empty(may not exist the key), try
json.optString("bye","callback string");
or
json.optString("bye");
instead.
In your demo code, the
JSONObject json = new JSONObject("{\"hello\":null}");
json.getString("hello");
this you get is String "null" not null.
your shoud use
if(json.isNull("hello")) {
helloStr = null;
} else {
helloStr = json.getString("hello");
}
first check with isNull()....if cant work then try belows
and also you have JSONObject.NULL to check null value...
if ((resultObject.has("username")
&& null != resultObject.getString("username")
&& resultObject.getString("username").trim().length() != 0)
{
//not null
}
and in your case also check resultObject.getString("username").trim().eqauls("null")
If you must parse json first and handle object later, let try this
Parser
Object data = json.get("username");
Handler
if (data instanceof Integer || data instanceof Double || data instanceof Long) {
// handle number ;
} else if (data instanceof String) {
// hanle string;
} else if (data == JSONObject.NULL) {
// hanle null;
}
Here's a helper method I use so that I can get JSON strings with only one line of code:
public String getJsonString(JSONObject jso, String field) {
if(jso.isNull(field))
return null;
else
try {
return jso.getString(field);
}
catch(Exception ex) {
LogHelper.e("model", "Error parsing value");
return null;
}
}
and then something like this:
String mFirstName = getJsonString(jsonObject, "first_name");
would give you your string value or safely set your string variable to null. I use Gson whenever I can to avoid pitfalls like these. It handles null values much better in my opinion.

Categories

Resources