Reputation: 29141
I'm importing multiple XML files that have the same tag names, but some of the files are without a few of the tags.
My imports work great for all files that have every "field" (ie <title></title>
), but I get java.lang.NullPointerException
when I try to set a value of my class to an item that doesn't exist in the XML file.
For example:
for(NewsItem item : parser.getParsedItems())
{
Article a1 = new Article();
a1.title = item.title.trim();
a1.subtitle = item.subhead.trim();
//...
}
This works great for most, but if one of them doesn't have a "subhead" tag, then I get the error.
Is there some way I can check IF it's been set or has value prior to trying to set it to the "title" value of my Article? (as an example).
I tried if(!item.title.isEmpty())
but that still gives the error.
(or is there a better way that I'm overlooking?)
Upvotes: 0
Views: 75
Reputation: 6862
Well, if the element doesn't exist, it can't be checked for isEmpty() because it is null.
if(item.title != null && !item.title.isEmpty()) {
// Yay, we have something useful!
a1.title = item.title.trim();
} else {
// Perhaps we should give a default value?
a1.title = "";
}
Upvotes: 1