How to handle empty response from DB? - java

I am fetching value from db in dbval variable. So I want to add condition, pass the case if the value equals "apple" or the value is empty or null. But if the value is diff like "orange" or "mango", throw error.
My code:
if (StringUtils.equals(apple, dbval) || dbval.equalsIgnoreCase(null) || dbval.isEmpty())
{
dbValueFlag = true;
logger.info("DB value matched ",);
}
else
{
logger.info("DB valuenot matched for pnac");
}

You can leverage Apache Commons StringUtils.isEmpty(str), which checks for empty strings and handles null gracefully.
Example:
System.out.println(StringUtils.isEmpty("")); // true
System.out.println(StringUtils.isEmpty(null)); // true
Or
if(str != null && !str.isEmpty()) { /* do your stuffs here */ }

Add throws InvalidArgumentException to your method signature. And throw this exception from the else block in your code.
public void thisIsYourMethod(String dbVal) throws InvalidArgumentException {
if (StringUtils.equals(apple, dbval) || dbval.equalsIgnoreCase(null) || dbval.isEmpty()) {
dbValueFlag = true;
logger.info("DB value matched ",);
} else {
logger.info("DB valuenot matched for pnac");
throw new InvalidArgumentException("Argument Passed in Wrong");
}
}

Related

Java 8 Optional: combine two possibly null object

I have to ensure if two values are non null. When the first and second have non null values, pass first as argument to second. If one of them are null value, then return false.
This can be done in the following piece of code:
String value1 = function_to_get_value1()
if (value1 == null) return false;
String value2 = function_to_get_value2(value1)
if (value2 == null) return false;
return true;
It can also be done in short form:
try {
return function_to_get_value2(function_to_get_value1()) != null;
} catch (NullPointerException e) {
return false;
}
I was wondering how to do this in fluent form with Optional.
You could try something like this:
return Optional.ofNullable(function_to_get_value1())
.map(v1 -> function_to_get_value2(v1))
.isPresent();
map() applies the lambda if value is present and returns a new Optional.ofNullable() or otherwise returns an empty Optional. So in the end you have an empty Optional if either value was null or a non-empty one.
If you have a look at the source code for those methods, it basically is equivalent to this:
//Optional.ofNullable(...)
Optional<UiObject> v1Opt = value1 == null ? Optional.empty() : Optional.of(value1);
//Optional.map(...)
Optional<UiObject> v2Opt;
if(v1Opt.isPresent()) {
//this is the lambda
UiObject value2 = function_to_get_value2(value1);
//Optional.ofNullable(...) called in map(...)
v2Opt = value2 == null ? Optional.empty() : Optional.of(value2);
} else {
v2Opt = Optional.empty();
}
//Optional.isPresent()
return v2Opt.value != null;

The method parseInt(String) in the type Integer is not applicable for the arguments (boolean)

I am getting the error The method parseInt(String) in the type Integer is not applicable for the arguments (boolean)
Here is the code
} else if (Integer.parseInt(answerField.getText() == null)) {
JOptionPane.showMessageDialog(null, "You did not enter an answer!");
}
I have also tried this but it doesn't work:
(Integer.parseInt(answerField.getText().equals("")))
&
(Integer.parseInt(answerField.getText().length()) == 0)
I just want to check to see if nothing has been entered and if so display a JOptionPane.
Edit: The var answerField is a JTextField, where the user inputs an answer of a mathematical question. So the ActionListener then determines if the answer is correct, hence the parseInt (because of it being a mathematical operation)
do {
checkButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (Integer.parseInt(answerField.getText()) == correctAnswer) {
count++;
JOptionPane.showMessageDialog(null, "Correct");
} else if (Integer.parseInt(answerField.getText().length()) == 0) {
JOptionPane.showMessageDialog(null, "You did not enter an answer!");
} else {
count++;
JOptionPane.showMessageDialog(null, "Incorrect!");
System.exit(0);
}
}
});
} while (count < 11);
Lets analise the code you have
(Integer.parseInt(answerField.getText() == null))
the parameter
answerField.getText() == null
return a boolean and the method Integer.parseInt(bool) is not defined in the Integer class.
It looks like you want to do:
else if (someConditionHere) {
Integer.parseInt(answerField.getText());
JOptionPane.showMessageDialog(null, "You did not enter an answer!");
}
all of the values inside of your parse int method return a boolean becuase they are performing a comparison between two values that result in either true or false. You should use Boolean.parseBoolean() to return either "true" or "false" strings
Integer.parseInt(answerField.getText() == null) is evaluated as
Integer.parseInt("someTextext" == null) then
Integer.parseInt(true/false)
Try to parse a boolean as an Integer will result as an error
To check is your field is null, only do if(answerField.getText() == null)
then if is not null you can try to parse the field value to an Integer the way you did.
I am not sure why you want to call Integer.parseInt, because you already have a boolean expression in your condition:
} else if (answerField.getText() == null) {
JOptionPane.showMessageDialog(null, "You did not enter an answer!");
}
Note that if conditions in Java can only accept boolean expressions, and you couldn't pass in an integer or whatever else you'd think of as truthy or falsy (unlike C or Javascript, for example).
If all you want to do is check to see if there's some string contained in answerField, then all you need to do is check to see if it's not null or empty.
if(!("".equals(answerField.getText()) || null == answerField.getText()) {
// other, non-integer-handling code here
}
You do not want to handle parsing the integer if there's an empty string or if it's null, since that could result in a NullPointerException.

Java: if, else and return

I am writing a method which contains if else statements, but also a return keyword. Now, I'm writing something like this:
public boolean deleteAnimal(String name) throws Exception{
if(name == null || name.trim().isEmpty())
throw new Exception("The key is empty");
else if(exists(name)){
hTable.remove(name);
}
else throw new Exception("Animal doesn't exist");
return hTable.get(name) == null;
}
I'm new in java and this is my first time trying to learn a programming language. I read that the 'else' statement excecutes always if the if condition is false.
Now, if these are false:
if(name == null || name.trim().isEmpty())
throw new Exception("The key is empty");
else if(exists(name)){
hTable.remove(name);
}
Shouldn't the else part always excecute?
else throw new Exception("Animal doesn't exist");
I noticed this since this method is returning true/false, and it seems like it's ignoring the else part, even when the conditions above it are false.
Without the knowledge about the rest of the code exists(String name) and the type of hTable (Map<String,? extends Object>) I need to guess:
If exits returns true, the else if statement evaluates to true. The line hTable.remove(name) will be executed. The else-branch is not invoked, because the else if was. Now the last line will return hTable.get(name) == null;
I think it will return true, because the hTable will return null.
I'll try to add comments to your snippet to help you understand the flow:
public boolean deleteAnimal(String name) throws Exception{
if(name == null || name.trim().isEmpty())
throw new Exception("The key is empty"); //Executes if 'name' is null or empty
else if(exists(name)){
hTable.remove(name); // Excecutes if 'name' is not null and not empty and the exists() returns true
}
else
throw new Exception("Animal doesn't exist"); //Excecutes if 'name' is not null and not empty and the exists() returns false
return hTable.get(name) == null; //The only instance when this is possible is when the 'else if' part was executed
}
Hope the comments helps you understand the flow!
With this in mind, the answer to your question is 'yes'.

Android Java exception even after string null or empty check

I really don't understand why java.lang.NumberFormatException: Invalid long: "null" happens here.
The problem snippet is like followings.
try {
userid = ((JSONObject) msg.obj).getString("userid");
if (userid.equals("") || userid.isEmpty() || null==userid) {
onClickLogout();
return;
} else {
client.setUserid(Long.parseLong(userid));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
onClickLogout();
return;
}
the line client.setUserid(Long.parseLong(userid)); gets following exception
java.lang.NumberFormatException: Invalid long: "null"
at java.lang.Long.invalidLong(Long.java:125)
at java.lang.Long.parse(Long.java:362)
at java.lang.Long.parseLong(Long.java:353)
at java.lang.Long.parseLong(Long.java:319)
at client.setUserid(Long.parseLong(userid));
The point is that the null exception occurs even after null and empty check of the userid in the code. What's wrong with me here? please check it out experts!
The string value and not reference is null.
You can add "null".equals(userid) to test for the literal null value in the if where you check for various forms of "no value".
Always check first for null value in your condition
if (null==userid || userid.isEmpty() || userid.equals("null") {
Then, in the next element of your condition, you are sure that userid is not null and no NullPointerException will be thrown
Also, in your case, check that userid does not contain the "null" String
Moreover userid.equals("") and userid.isEmpty() are the same thing.
You can check null with utility method isEmpty from TextUtils,
public static boolean isEmpty(CharSequence str) {
return str == null || str.length() == 0;
}
isEmpty(CharSequence str) method check both condition, for null and length.

Android: Can't check whether a string variable is null or not. How to check if a string variable is null or not?

I can't check whether a string is empty or not coming from rest service as input stream which then I am changing into string for parsing.
public boolean isNullorEmpty(String string)
{
if(string !=null || !string.isEmpty() || string.length()>0)
return true;
else
return false;
}
Please help me out to check if string is empty or not.
The current problem in your code is that if the string you pass in argument is null, thenstring !=null is evaluated to false. Hence you'll try to evaluate !string.isEmpty() which will lead to a NullPointerException.
On the other hand if you pass a String that is not null (ex "" or "test"), string != null is evaluated to true and hence you return true.
So to fix that you should, as the name of your method suggests, check if the String is null OR empty.
But since you're on android, don't reinvent the wheel and use TextUtils.isEmpty(CharSequence str).
boolean isEmpty = TextUtils.isEmpty(myString);
Returns true if the string is null or 0-length.
If you want to look about how is it implemented:
427 public static boolean isEmpty(CharSequence str) {
428 if (str == null || str.length() == 0)
429 return true;
430 else
431 return false;
432 }
Well, this can be handled in plain java like:
And it can be written like:
public boolean isStringEmpty (){
if(str ==null || str.isEmpty () || str.trim().equals("")){
return true;
}
return false;
}

Categories

Resources