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"));
}
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
So I have an issue. My RPC calls will fail due to "NullpointExeption". Meaning that one column contains null in value. This is done on purpose, as I am gonna fill this column with value at some time. How can I allow the Java code to ignore/ or allow this error to happen thru error handling??
#Override
public List <BreakRegistered> getAllRegisteredBreaks() throws IllegalArgumentException {
List<BreakRegistered> resultsfromquery = null;
ResultSet resultSet = null;
try {
//Execute query kaldes på resultsetter, fordi der kun nedhentes data
resultSet = getAllEmployeesBreaks.executeQuery();
resultsfromquery = new ArrayList<BreakRegistered>();
while (resultSet.next()) {
resultsfromquery.add(new BreakRegistered(
resultSet.getTimestamp("time").toString(),
resultSet.getTimestamp("checkedOut").toString(), //Error occurs HERE!
resultSet.getString("navn"),
resultSet.getInt("medarbejderID")));
}
} catch (SQLException sqlException) {
throw new IllegalArgumentException(" \"getBreaks\" fejlede");
} finally {
try {
resultSet.close();
} catch (SQLException sqlException) {
sqlException.printStackTrace();
close();
}
}
return resultsfromquery;
}
The implication is that resultSet.getTimestamp("checkedOut") is returning null. You need to check for that before you try to deference the object to call toString().
A typical construct for this might be:
Object time = resultSet.getTimestamp("checkedOut"); //Or use a more specific type
String timeAsString;
if ( time != null)
timeAsString = time.toString();
else
timeAsString = null; // or empty string, or any other placeholder value you want
P.S. It looks like you are executing SQL queries. I would not call those "RPC calls".
You just need to check whether it is null. If you will use this query result later, It would be nice to put the logic into Object. Moreover, In this case, you just need to change the constructor if there will be some changes to your DB in the future.
public BreakRegistered(ResultSet resultSet) {
this.time = resultSet.getTimestamp("time") != null ? resultSet.getTimestamp("time").toString() : null;
this.checkedOut = resultSet.getTimestamp("checkedOut") != null ? resultSet.getTimestamp("checkedOut").toString() : null;
this.navn = resultSet.getString("navn");
this.medarbejderID = resultSet.getInt("medarbejderID")
}
i have a signup page connected to sql database.now i want to have validations in signup page like firstname,lastname,username etc can not be empty using java how can i do that
My code is
String fname=Fname.getText();
String lname=Lname.getText();
String uname=Uname.getText();
String emailid=Emailid.getText();
String contact=Contact.getText();
String pass=String.valueOf(Pass.getPassword());
Connection conn=null;
PreparedStatement pstmt=null;
try
{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/zeeshan","root","sHaNi97426");
pstmt=conn.prepareStatement("Insert into signup1 values(?,?,?,?,?,?)");
pstmt.setString(1,fname);
pstmt.setString(2,lname);
pstmt.setString(3,uname);
pstmt.setString(4,emailid);
pstmt.setString(5,contact);
pstmt.setString(6,pass);
int i=pstmt.executeUpdate();
if(i>0)
{
JOptionPane.showMessageDialog(null,"Successfully Registered");
}
else
{
JOptionPane.showMessageDialog(null,"Error");
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,e);
}
First your question is not direct. Validation occurs before database query. You should not proceed to database Connetction or making any query.
What should you do:
public static boolean nullOrEmpty(String value) {
return value == null || value.trim().equals("") ? true : false;
}
public void yourMethod(){
try{
//YourCode Here
String fname=Fname.getText();
if(nullOrEmpty(fname)){
new throw ValidationException("First name should not be null.");
}
//YourCode Here
}catch(ValidationException e){
System.err.println("Exception:"+e.getMessage());
}
}
Check for every string to validate.
that should not be hard, you can do it with simple if and else like below
if(fname != null && fname.isEmpty()){
throw new Exception(fname+" cannot be empty");
}else if(lname != null && lname.isEmpty()){
throw new Exception(fname+" cannot be empty");
}
.....
as a recommendation you should abstract validation and database access objects . see example of MVC here
You may do it just by downloading a jar named org.apache.commons.lang
Stringutils Class Reference
Sample Code
StringUtils.isBlank(null) = true
StringUtils.isBlank("") = true
StringUtils.isBlank(" ") = true
StringUtils.isBlank("bob") = false
StringUtils.isBlank(" bob ") = false
or
StringUtils.isEmpty(obj_String); // Another method to check either null or "";
To check if a String is empty you can use the method .isEmpty(). You'll probably want to use .trim() first, as this removes all the whitespaces at the beginning and ending of the String. For more options check out the full documentation here.
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;
}
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.
I need to know if there is a way to say that int type is not found in Java Android.
I'm writing an android application,which is actually written first for Iphone, and have a little issue. At some point I have to check if the int type which returns a method is not found and if it's true do some calculations. The problem is that when I did that in Java as if(Id==0) it's throwing me an exception even if the Id is 0.
this is my method :
private static int localUserIdByServerUserId(int serverUserId, String serverName){
dbHelper = new DataBaseHelper(context, "stampii_sys_tpl.sqlite", null, 1);
dbHelper.getDatabase();
String query = "SELECT id FROM users WHERE objectId = "+serverUserId+" AND serverName = '"+serverName+"' LIMIT 1";
ArrayList<String> result = new ArrayList<String>();
cursor = dbHelper.executeSQLQuery(query);
cursor.moveToFirst();
while(!cursor.isAfterLast()) {
result.add(cursor.getString(cursor.getColumnIndex("id")));
cursor.moveToNext();
}
Log.i("result ","Result : "+result.toString());
Log.i("CURSOR ","Cursor Position : "+cursor.getPosition());
int uuid = Integer.parseInt(result.get(cursor.getColumnIndex("objectId")+1));
Log.w("localUSerByIdServerUserId","LocalUserByIdServerUserId result : "+uuid);
cursor.close();
return uuid;
and here is how I'm using it :
int uuId = rpc.lUserIdByServerUserId(userId,newServerName);
Log.w("uuId","uuId : "+uuId);
if(uuId==0){
// do some calculations
}
Any suggestions ?
lUserIdByServerUserId() could throw an exception when the user is not found.
e.g.
try {
int uuId = rpc.lUserIdByServerUserId(userId,newServerName);
Log.w("uuId","uuId : "+uuId);
}
catch (NotFoundException nfe) {
// do some calculations
}
You will need to modify lUserIdByServerUserId() to throw the exception. You may also need to define your own NotFoundException class if a suitable exception doesn't already exist in the Java libraries.
EDIT:
Alternatively, following on from #mthpvg's answer, you could change lUserIdByServerUserId() to return an Integer type, which can be set to null if not found and tested.
e.g.
Integer uuId = rpc.lUserIdByServerUserId(userId,newServerName);
if (uuId == null) {
// Do some calculations
}