Reputation: 415
How can I avoid NullPointerExceptions
? I have tried using try-catch
blocks but that didn't work.
My program is supposed to get data from Google Calendar. I am getting many elements, but here it is just one element as an example...
for (Iterator<?> i = eventsToday.iterator(); i.hasNext();) {
Component component = (Component) i.next();
String Attachement=null;
if(component.getProperty(Property.ATTACH).toString().trim()!=null){
Attachement=component.getProperty(Property.ATTACH).toString();
}
}
Could someone please help me with this.
Upvotes: 0
Views: 161
Reputation: 6432
Test if component.getProperty() == null
the null pointer exception is due to the toString()
being called on a null object. The following example will work. (replace Object o
with the real type returned by getProperty()
)
String Attachment;
Object o = component.getProperty(Property.ATTACH);
if(o != null) {
Attachment = component.getProperty(Property.ATTACH).toString();
}
Upvotes: 7
Reputation: 92304
Problem is likely that
component.getProperty(Property.ATTACH)
is returning null
Just add some code that checks
if (component.getProperty(Property.ATTACH)) {
Attachement = component.getProperty(Property.ATTACH).toString();
}
You probably want to cache component.getProperty(Property.ATTACH)
Upvotes: 0