Android Java exception even after string null or empty check - java

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.

Related

How to handle empty response from DB?

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");
}
}

java for loop that runs list executes only once

The for loop in the code below only executes once. I was looking at similiar questions but those have something that breaks it like editing the list in the loop while I dont.
public String getProfileList(JSONObject obj, String uuid) {
JSONObject profile = (JSONObject) obj.get("profiles");
#SuppressWarnings("unchecked")
ArrayList<String> list = new ArrayList<String>(profile.keySet());
System.out.println(list);
for (String object: list) {
System.out.println(object);
String isUUID = (String) ((JSONObject) profile.get(object)).get("mpm-data:uuid");
System.out.println(object + " == " + isUUID);
if (isUUID.equals(uuid)) {
System.out.println("TRUE");
return object;
}
}
System.out.println("no profile found.");
return null;
}
This code outputs this:
[5fb4acd48e7d422eabecd82e32fb03c6, 44d01181eae635d31f2cefe5e1f75cd4,e0e96e422659dfdc1ad16d53a37ee618, a3ae7136f900457290e99bd657db0385]
5fb4acd48e7d422eabecd82e32fb03c6
5fb4acd48e7d422eabecd82e32fb03c6 == null
For your console output you can see that isUUID is null. This means that when you attempt to call its method equals there is actually no object to call it to and you should be getting a NullPointerException. That's why it is best to do equals assertions with the part you know will not be null on the left side:
uuid.equals(isUUID) would be better.
Notice that if you do an equals assertion with a variable and a static string then it is best to do it like so:
"myCompareString".equals(myVariable), since "myCompareString" can never be null whereas myVariable can.
if (isUUID.equals(uuid)) will throw a nullPointerException when isuuid is null.
You should check if the data is right, and handle the exception.
And you can use StringUtils.equals(String str1, String str2) in commons-lang.jar, then you don't need to handle the null yourself, see http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html
System.out.println(object + " == " + isUUID);
Code prints
5fb4acd48e7d422eabecd82e32fb03c6 == null and next statement you are using in if condition .If isUUID is null it should throw null pointer exception.Can you please check this point
if (isUUID.equals(uuid)) {
System.out.println("TRUE");
return object;
}

Check if EditText with "inputType = number" is null

I am trying to check if the input in EditText in null or not .
if(editTextSum.getText().toString() != null) {
userStartingBalance = Integer.valueOf(editTextSum.getText().toString());
} else {
userStartingBalance = 0;
}
Here userStartingBalance is Integer type .
But I am getting an error everytime that
Can't convert " " into int , and the line is pointed to the 'if case' if I don't enter anything.
Why is it not going to else case?
What should be the workaround?
You are not properly handling the case in which your EditText simply has no content in it.
In this case, editTextSum.getText().toString() will not return null (in fact, that should never be null). Instead, it will return an empty string.
Instead, you might want to try editTextSum.getText().toString().isEmpty() instead,. isEmpty() will return true if the length is 0.
try:
Integer.parseInt(editTextSum.getText().toString())
Why is it not going to else case ?
Because you are calling ToString() on Null. If the field has no value present then it wil set NULL to it and if you try to run the toString() method you will receive this error. Do the Null check before retrieving the value.
Workaround
if( editTextSum.getText() != null )
{
userStartingBalance = Integer.parseInt(editTextSum.getText().toString());
}
else
{
userStartingBalance =0;
}

My method keeps saying I need to return a string but my method has a return statement that returns a string

I have a method that is suppose to go get a JSON object that has all the champion ids from league of legends and I want it to return the name of the champion based on the "number" that is passed to the method from another loop in the program.
public String getChampionName(int number) //where it is saying its not returning a string
{
try
{
String JSonChampionName = readURL("myURLwithAPIkey");
JSONObject object = JSONObject.fromObject(JSonChampionName);
JSONObject championData = (JSONObject)(object.get("data"));
JSONObject champName = (JSONObject)(championData.get(number));
if(object != null && championData != null && champName != null)
{
String cName = champName.get("name").toString();
return cName;
}
else
return "";
}catch(Exception v){}
}
Any ideas I am just not sure why its telling me the method is not returning a string.
What if there is an Exception caught? In that case your method doesn't have a return statement.
Either don't catch the Exception, or provide a return statement in the case that the Exception is caught.
The compiler is saying you need to return a string on every possible path that the program could take. If an exception occurs, you will catch it, but your catch block will do nothing; then the program will fall to the end of the method without returning anything.
You need to fix your method so that if an exception is caught, you either return something, or throw some other exception.
You would need to return the type expected in all scenarios!! Thats what compiler expects.
Right now , with the code that you implemented , the problem is that in case of an exception this method does not return anything...
Thats why compiler is complaining even though you have a return statement..

compare an integer to a null value

I need to see if a text field has an empty value. I need to see if
if(Double.parseDouble(distanceTf.getText())==0)
I know 0 won't work. I also know null won't work and I know .equals won't work.
Does anyone know how I can compare this line of code to a null value?
if (stageTf.getText().equals("") || Double.parseDouble(distanceTf.getText()) == null) {
JOptionPane.showMessageDialog(null, "You did not enter both a stage number and distance");
return;
}
Thanks for all the above replies but they don't work.
The part of the code I have trouble with is:
if (Double.parseDouble(distanceTf.getText())==null)
The rest of it is fine.
I have tried putting this outside the if statement and using distanceTf.getText().equals("")
in the if statement but this doesn't work either.
I just can't find out how to assign an empty value to the line of code for a double.
I know null, .equals or "" won't work.
You're not clear on which value could be null, so I'll assume both.
Since Double.parseDouble requires a non-null argument, you need to check it for null.
if(null != distanceTf.getText() && Double.parseDouble(distanceTf.getText()) != 0.0)
stageTf.getText() could return null too, but if you're guaranteed to be comparing a known non-null String against null, it would return false. So, this comparison is safer:
if("".equals(stageTf.getText())
The important thing to understand is: what you mean with null value? A null reference or an empty string?
You could do
stageTf.getText().isEmpty()
to check if the string is empty and parse it only if it contains something.
// here remember it's still wrong
if (!stageTf.getText().isEmpty() && Double.parseDouble(distanceTf.getText()) == null) {
Second problem: Double.parseDouble doesn't return null since it returns a native type.. it thrown an exception if something went wrong. So you can catch NumberFormatException.
Then you could write:
try {
double result;
if (!stageTf.getText().isEmpty() && (result = Double.parseDouble(distanceTf.getText()))) {
/* i think you need the result of the conversion, so i saved it in result */
}
}
catch (NumberFormatException e) { /* something went wrong! */ }
You need to test if the field is empty first. You did it correctly with your first conditional on the stageTf field. You need to do the same with the distanceTF field. This means nesting your conditional statements.
if(stageTF.getText().equals(""))
if(distanceTF.getText().equals("")){
/* ... */
} else {
//here it is safe to test for exceptions by using a try/catch
try{
//here you can parse the string to your Double
}catch(NumberFormatException nfe){ /* ... */ }
}
first of all you should check for null before empty because if the value is null you'll get a NullPointerException on the first one.
Second you'll get a NullPointerException if distanceTf.getText() is null on the Double.parseDouble
Double.parseDouble() doc
what I would do is create a method validate as follows:
private boolean validate(String field){ //where field = stageIf.getText() for example
if(field != null && field.trim().length() > 0)
return true;
else return false;
}
Parse outside if statment, then just compare :
if(distanceTf.getText() == "")

Categories

Resources