zoy.khan
zoy.khan

Reputation: 87

Last child of XML throws NullPointerException

Here is my problem, this code below can delete all children from a node, however, when there is one last child remaining, it throws a nullpointer. In particular, I am focused on deleting the pose, if I have 10 of them, I can delete 9, but the last one, will throw nullpointer.

The screen shot of a enter image description here enter image description here

Here is my code:

 for(int j = 0; j<dom.getElementsByTagName("animation_sequence").getLength(); j++)
 {
   NamedNodeMap attributes = dom.getElementsByTagName("pose").item(j).getAttributes();
   for (int a = 0; a < attributes.getLength(); a++) {
     Node theAttribute = attributes.item(a);
     if(PoseSelectionListener.imageIDOfSelectedPose.equalsIgnoreCase(
                         attributes.item(a).getNodeValue().toString()))
     {
       if(removed==false)
       {
         Node temp = dom.getElementsByTagName("pose").item(j);
         removed=true;

         try{
           temp.getParentNode().removeChild(temp);
         }
         catch(NullPointerException ex) {return;}
       }
     }

Upvotes: 0

Views: 261

Answers (1)

Frank Pavageau
Frank Pavageau

Reputation: 11715

You're counting the "animation_sequence" elements, but then using the index to access a "pose" element, so if there are more "animation_sequence"s than there are "pose"s, you're bound to get an error of some kind.

Upvotes: 2

Related Questions