VICKY-TSC
VICKY-TSC

Reputation: 415

Can't locate origin of null pointer exception

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

Answers (2)

secretformula
secretformula

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

Ruan Mendes
Ruan Mendes

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

Related Questions