I'm to trying to make an android app where I accept input from the user using the speech Recognition server. I'm capturing the results in a ArrayList as follows :
matches = data.getStringArrayListExtra(
RecognizerIntent.EXTRA_RESULTS);
matches is declared globally as :
ArrayList<string> matches;
Now I want to check if the user has spoken a particular word. So I do this :
if(matches.contains("TextToBeDetected")) { }
But the line above throws a NullPointerException.
Please help.
P.S Yes, I'm a Java and Android newbie.
Obviously, your matches is null. As per the Intent documentation, http://developer.android.com/reference/android/content/Intent.html#getStringArrayListExtra%28java.lang.String%29
getStringArrayListExtra returns null if the key is not found in the bundle.
Test for nullity before testing if it contains anything
It sounds as though getStringArrayListExtra is returning null (the docs say it will if there is such ArrayList value found), and so when you try matches.contains("TextToBeDetected") it fails because you're trying to dereference a null reference. You'll want to check the return value from getStringArrayListExtra to make sure it's not null before you use it. E.g.:
matches = data.getStringArrayListExtra(
RecognizerIntent.EXTRA_RESULTS);
// ...
if (matches != null) {
if (matches.contains("TextToBeDetected")) {
// do something
}
}
If you see the docs Android.Content.Intent.GetStringArrayListExtra It says
the value of an item that previously added with putExtra() or null if no ArrayList value was found.
You need to check for the list being null before setting it to matches.
Are you sure that matches is allocated?
Try this, and look at your logcat output:
if (matches == null) {
Log.d("YourAppName", "matches is null!");
} else if (matches.contains("TextToBeDetected")) {
Log.d("YourAppName", "matches does contain TextToBeDetected");
} else {
Log.d("YourAppName", "matches does not contain TextToBeDetected");
}
data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)
will return the value of an item that previously added with putExtra() or null if no ArrayList value was found. In your case, maybe it returned null
Related
Here is my code
if (!multipartFile.isEmpty() && multipartFile.getOriginalFilename() != null && !multipartFile.getOriginalFilename().isBlank()) {
String fileName = StringUtils.cleanPath(multipartFile.getOriginalFilename());
dishCreationDto.setImageFileName(fileName);
dishService.saveWithFile(dishCreationDto, multipartFile);
} else {
dishService.save(dishCreationDto);
}
Here is how I see that code
As you can see, the last part of IF condition is underlined as Idea thinks that getOriginalFilename can return null, but I've checked this with that line of a code
multipartFile.getOriginalFilename() != null. What am I doing wrong?
Idea thinks that getOriginalFilename can return null
Because it can.
but I've checked this with that line of a code multipartFile.getOriginalFilename() != null
You checked that the previous invocation did not return null. The next one still can.
What am I doing wrong?
Calling a method twice in rapid succession, instead of storing its result in a variable and using that one for the check and the further processing. In fact you then call it for a 3rd time.
(this was just a copy of my comment from above)
While there may be ways to simplify the condition as the other answer shows, as you also need the result of getOriginalFilename() inside the if, I would assume the IDE will complain about that one next, and at the end you will probably have to bite the bullet and have a variable for it:
String originalFilename = multipartFile.getOriginalFilename();
if (!multipartFile.isEmpty() && originalFilename != null && !originalFilename.isBlank()) {
String fileName = StringUtils.cleanPath(originalFilename);
dishCreationDto.setImageFileName(fileName);
dishService.saveWithFile(dishCreationDto, multipartFile);
} else {
dishService.save(dishCreationDto);
}
You could simplify that expression by using the StringUtils:
!StringUtils.isNullOrEmpty(multipartFile.getOriginalFilename())
There are other functions in that utility class that might be helpful depending on what you're trying to do.
IntelliJ isn't always right but is always good to look a bit more in detail to our code to see what can be improved/simplified for better debugging/readability.
I'm working with on a Java program that checks a config file integrity.
On some point, I need to ensure that some mandatory values are setted up, either give it a default value.
So, I made a HashTable<String, String> working like a key => value table. On this table I store all the configuration lines on the file, and then I check it.
The problem comes when a specific value does not exist, for example:
String p = null;
/*...*/
//here I'm trying to get the LOG value
p = this.PAIRS.get("LOG");
if(p.equals(null) || p.equals("")){
//set default value
}
The problem is that I'm getting a NullPointerException, so it would be fine if someone can help me on how to determinate if this.PAIRS.get("LOG"); found a key or not...
Thanks!
EDIT: Solved, the right thing was using == and not an equals.
Thanks again!
If p is null, a NullPointerException will be thrown because it is not an instance of an Object (so the equals method doesn't exist). Checking for null should be done the following way : p == null
p = this.PAIRS.get("LOG");
This code return null if the key is not present and when you are doing below statement it will throw exception
if(p.equals(null) || p.equals("")){
//set default value
}
Instead check null first then do .equals
if(p==null || p.equals("")){
//set default value
}
I think is a bad idea to return null values so I am looking to an alternative to this.
Here is my code:
public Flight getFlight(String id) {
for (Flight f : this.flightList ) {
if ( f.getId().equals(id))
return f;
}
return null;
}
I am looking for a certain Flight with a certain id and I want to return it.
If I return null I have to check every time if the object I returned is null or not. And I would like to avoid this if possible.
So any suggestions are welcome.
This really depends if the event "a flight was not found" is considered exceptional or not.
When you call this method, if the calling code expects a valid flight all the time then not finding it is exceptional. There should be a flight but there isn't one. In this scenario, it is best to throw a custom Exception like FlightNotFoundException, that contains the id of the searched flight. It would typically be a RuntimeException: the flight should have been there, there is nothing you can do to recover from this.
However, if this requirement is not met, I don't see anything wrong with returning null, as long as this is correctly documented.
You can take a look at Null object pattern (in C# is implemented as string.Empty), since it
replaces check of NULL object instance. Instead of putting if check for a null value, Null Object reflects a do nothing relationship. Such Null object can also be used to provide default behaviour in case data is not available.
In your case it could be something like:
public class NullFlight extends AbstractFlight {
#Override
public String getId() {
return "Not Available for null Flight!";
}
#Override
public boolean isNil() {
return true;
}
}
Also this is a valid case when dealing with collections, you should return 'new' empty ones instead of Null.
Generally returning null instead of an object is a bad practice. There are two alternatives to returning null.
Fistly I would recommend to check out Null Object Pattern with defined neutral ("null") behavior.
The second idea is to thrown your own Exception when you can't return an object.
if ( f.getId().equals(id)){
return f;
}else throw new FlightNotFoundException();
I've been struggling to find why my if statement didnt work properly so I used a try catch block instead. This is the if statement as I had it:
//selectArtistByName returns an Artist object
if (!selectArtistByName(artist.getName()).equals(artist.getName()) ||
selectArtistByName(artist.getName())==null) {
//save data to database
}
When I ran the above, I got a NullPointerException because the method selectArtistByName was returning null as the database was empty. What I don't understand is why it didn't go in the if statement when I was getting null. So I did this and it worked:
try {
if (!selectArtistByName(artist.getName()).equals(artist.getName())) {
}
} catch (NullPointerException e) {
m_db.insert(TABLE_ARTIST, null, artistContents);
}
I'm not a Java guru but it looks like a horrible fix to me. How could I fix this.
You just need to change the order of condition in if block:
if (selectArtistByName(artist.getName()) == null ||
!selectArtistByName(artist.getName()).equals(artist.getName())) {
//save data to database
}
Do the null check first.
If that succeeds, then 2nd condition is not evaluated, and hence no NullPointerException. This is how short-circuit OR operator works. It only evaluates the 2nd expression, if 1st one evaluates to false.
If null check fails, then 2nd condition is evaluated, which wouldn't throw NPE, as it has already been confirmed by first condition.
Also, as rightly pointed out by #ruakh in comment, your condition seems to be broken. selectArtistByName sounds to be returning an Artist, which you can't compare with String.
I guess, you don't even need the 2nd condition. I would assume, selectArtistByName() method has already done the equality check for name, based on which it will return Artist. Just check that selectArtistByName method return null, that would be enough. So, you should change the if block to:
if (selectArtistByName(artist.getName()) == null) {
//save data to database
}
Just put the null condition check at the beginning to shortcut when artist is unknown:
if (selectArtistByName(artist.getName())==null || !selectArtistByName(artist.getName()).equals(artist.getName())) {
//save data to database
}
You can find more info about lazy evaluation in this other question: Does Java have lazy evaluation?
OMG. I have a little project to do and the Strings are killing me!
Now, I have a String which is null (is taken the value from invoking getParameter() from a servlet).
The problem is that, I'm trying to see if it's null, and, even if it's null, in the program is telling me that is not null, but later in program, when I'm using the variable, I receive a exception saying the variable is null.
System.out.println("In " + ID); // in console: In null
if ((ID == null) || (ID == "null") || ID.equals(null) || **ID.equals("null")**)
{
// after I put the 4th condition, the if is working right (WHAT IS THE PROBLEM?)
System.out.println("==null");
this.ID = "";
}
else
{
System.out.println("!=null");
this.ID = ID;
}
System.out.println("After " + ID);
What I'm doing wrong?
Only the forth condition is working! What about the rest(except second one, because that condition i put it because I was desperate)
I taught ID == null or ID.equals(null) will be ok, but no.
Edit:
The problem is that, I'm getting the value of the ID from a form(form 1 let's say- usually). But in this case, I'm using form 2 which doesn't have any ID inputs, so ID must be null and not "null"
ID.equals("null")
Clearly, ID contains the four-letter string "null". So it's not null (the value for "nothing").
See the Java glossary for more on the null constant. Basically a variable has the value null if it does not reference any object. The string "null" is an object however, namely an instance of the class String, and in this case the variable ID references this object.
(Note that by convention Java variables start with a lower case letter, and acronyms like ID are written completely lower case, so write id instead of ID.)
Here are the four tests you've tried. The first and the fourth are the only ones that you should need.
ID == null : is the field 'ID' null?
ID == "null": is the ref for the field 'ID' the same as the newly allocated String "null"? This should generally return false.
ID.equals(null): this should always return false - conceptually were this ever true you should throw a NullPointerException.
ID.equals("null"): is the value of the String 'ID' the same as the value of the String "null"?
Since you get the string from a servlet i can say that this is normal.
Java converts a null string to a "null" string on some conditions.
Obviously the string you retrieve is not a null value, but it is a 4 char string "null"
Why don't you try debugging? Or just see what does this return:
System.out.println("Length of ID: " + ID.Length);
Edit: If you don't get exception here, this means that the string is not null and also output "Length of ID: 4" will mean that the string is really ID = "null"
EDIT2: Alright it seems that some guys do not understand what is going on here and they say how can a null string be "null" in some conditions in Java? They find it riddiculus. I prefer them to try this on java:
String abc = null;
String xyz = "hello";
System.out.println(xyz + abc);
The output will be "hellonull" Nothing else...
Also here we have a servlet. There is a null data. Servlet sends the null data as "null" what should it do? An empty string? Come on!!! "
Looks like it is return the String "null" and not a Null Object.
If the result was actually a null then
ID == null
would suffice, but as is mentioned the string value of ID is obviously "null" rather than the null object.
You should use .equals when comparing strings rather than using ==
This blog explains more about his:
http://blog.enrii.com/2006/03/15/java-string-equality-common-mistake/
So, "null" does not equal null, in Java.
If the value is coming from a Servlet then the container is most likely converting an empty form field to a blank string. You should do a check against null and blank ("").
if (value==null || value.equals(""))
Alternatively you can use String's isEmpty() method:
if (value==null || value.isEmpty())
If the value of your variable ID is the string literal "null", then I would guess that there is a bug earlier in the code when you retrieve it using the getParameter() method. According to the docs, the getParameter() method is supposed to return null (the null reference) if there is no value for the specified name. This indicates that somewhere you are doing an operation that converts the result to the string literal, perhaps concatinating with the empty string (i.e. ID + "" ; )