I\'m guessing I\'m getting this error because the string is trying to substring a null value. But wouldn\'t the \".length() > 0\" part eliminate
I would recommend apache commons lang. A one-liner takes care of the problem.
pstmt2.setString(3, StringUtils.defaultIfEmpty(
StringUtils.subString(itemdescription,0, 38), "_"));
It is a pity that substring is not implemented in a way that handles short strings – like in other languages e.g. Python.
Ok, we cannot change that and have to consider this edge case every time we use substr, instead of if-else clauses I would go for this shorter variant:
myText.substring(0, Math.min(6, myText.length()))
You must check the String length. You assume that you can do substring(0,38) as long as String is not null, but you actually need the String to be of at least 38 characters length.
itemdescription is shorter than 38 chars. Which is why the StringOutOfBoundsException is being thrown.
Checking .length() > 0 simply makes sure the String has some not-null value, what you need to do is check that the length is long enough. You could try:
if(itemdescription.length() > 38)
...
Should anyone face the same problem.
Do this: str.substring (...(trim()) ;
Hope it helps somebodies
if (itemdescription != null && itemdescription.length() > 0) {
pstmt2.setString(3, itemdescription.substring(0, Math.min(itemdescription.length(), 38)));
} else {
pstmt2.setString(3, "_");
}