Java NullPointerException javax.xml.transform -


i wrote simple xmlphonebook program inputs such firstname, lastname , phone number user (from input console) , saves xml file called "phonebook.xml". program checks existing xml file , updates file if exist or else creates new file. first version code wrote without error handling class successful.

when tried update code error handling class thats when started getting nullpointerexception javax.xml.transform. have posted both versions of code below understanding.

main class xmlphonebook without error handling.

    /**      *      * @author sanjayan ravi      */     /**      *      * class xmlphonebook main class controls getcontactinfo function , storecontactinfo.      */     public class xmlphonebook      {         getcontactinformation gci;         storecontactinformation sci;          xmlphonebook()         {             gci = new getcontactinformation();         }         /**         *         * getcontactinfo function triggers functions getfirstname, getlastname, getphonenumber of getcontactinformation class.         */         void getcontactinfo(){             gci.getfirstname();             gci.getlastname();             gci.getphonenumber();         }         /**         *         * variables fname, lname, phonenumber of class getcontactinformation contains user entered data, these values passed class storecontactinformation creating/updating xml file user data.         */         void storecontactinfo(){             sci = new storecontactinformation(gci.fname,gci.lname,gci.phonenumber);         }         public static void main(string[] args)          {             xmlphonebook pb = new xmlphonebook();             pb.getcontactinfo();             pb.storecontactinfo();         }      } 

class getcontactinformation without error handling.

    /**     *     * class getcontactinformation responsible getting inputs user such first name, last name , phone number.      * variables fname(string), lname(string), phonenumber(long) used containing user data during run time.     * variable reader(scanner) used getting inputs user via console.     */     import java.util.scanner;      public class getcontactinformation {         string fname;         string lname;         long phonenumber;         scanner reader;          getcontactinformation(){             fname=null;             lname=null;             phonenumber=0;         }         /**          *          * function getfirstname prompts user first name , gets inputs console.          * value first name passed function setfirstname.          */         void getfirstname(){             system.out.println("enter firstname = ");             reader = new scanner(system.in);             setfirstname(reader.nextline());         }          /**          *          * function getlastname prompts user last name , gets inputs console.          * value last name passed function setlastname.          */         void getlastname(){             system.out.println("enter lastname = ");             reader = new scanner(system.in);             setlastname(reader.nextline());         }          /**          *          * function getphonenumber prompts user phone number , gets inputs console.          * value phone number passed function setphonenumber.          */         void getphonenumber(){             try{                 system.out.println("enter phonenumber = ");                 reader = new scanner(system.in);                   setphonenumber(long.parseunsignedlong(reader.nextline()));             }catch(java.lang.numberformatexception e){              }          }         /**          *          * function setfirstname assigns value receives variable fname.          */         string setfirstname(string fn){            return  fname=fn;         }         /**          *          * function setlastname assigns value receives variable lname.          */         string setlastname(string ln){             return  lname=ln;         }          /**          *          * function setphonenumber assigns value receives variable phonenumber.          */         long setphonenumber(long pn){             return  phonenumber=pn;         }     } 

last class storecontactinformation without error handling.

    /**      *      * storecontactinformation responsible storing user data such first name, last name , phone number xml file called phonebook.xml.      * storecontactinformation first checks if xml file exist if file exist updates file or else creates new xml file provided user data.      *      */     import java.io.file;     import javax.xml.parsers.documentbuilder;     import javax.xml.parsers.documentbuilderfactory;     import javax.xml.parsers.parserconfigurationexception;     import javax.xml.transform.transformer;     import javax.xml.transform.transformerexception;     import javax.xml.transform.transformerfactory;     import javax.xml.transform.dom.domsource;     import javax.xml.transform.stream.streamresult;     import javax.xml.transform.outputkeys;      import org.w3c.dom.attr;     import org.w3c.dom.document;     import org.w3c.dom.element;      import org.xml.sax.saxexception;     import java.io.ioexception;     import org.w3c.dom.node;     import org.w3c.dom.nodelist;      public class storecontactinformation {          file f;         string filepathstring ;         documentbuilderfactory docfactory ;         documentbuilder docbuilder ;         document doc;         transformerfactory transformerfactory;         transformer transformer;         domsource source;         streamresult result;         string firstname;         string lastname;         long phonenumber;          storecontactinformation(string fn, string ln, long pn){              filepathstring="phonebook.xml"; //file path current working directory.              f = new file(filepathstring);             firstname=fn;             lastname=ln;             phonenumber=pn;             docfactory = documentbuilderfactory.newinstance();             try {                 docbuilder = docfactory.newdocumentbuilder();                 }             catch (parserconfigurationexception pce)                  {                     pce.printstacktrace();                 }              transformerfactory = transformerfactory.newinstance();             try                  {                     transformer = transformerfactory.newtransformer();                 }             catch (transformerexception tfe)                 {                     tfe.printstacktrace();                 }             // check if xml file exist !                     if(f.exists() && !f.isdirectory()) {                 //if exist                 updatexmlfile();                 writetoxmlfile();              }else{                 //if not exist                 createxmlfile();                  writetoxmlfile();             }           }         /**         *         * function createxmlfile creates new xml file if 1 doesn't exist already.          * first set of data stored in xml file given unique id="1".         * root element of xml file "contactinformation" contains child nodes "contact" there unique ids.         * element "contact further contains child nodes "firstname","lastname" , "phonenumber".         */         void createxmlfile(){              doc = docbuilder.newdocument();             element rootelement = doc.createelement("contactinformation");             doc.appendchild(rootelement);             element contact = doc.createelement("contact");             rootelement.appendchild(contact);             attr attr = doc.createattribute("id");             attr.setvalue("1");             contact.setattributenode(attr);             element firstname = doc.createelement("firstname");             firstname.appendchild(doc.createtextnode(firstname));             contact.appendchild(firstname);             element lastname = doc.createelement("lastname");             lastname.appendchild(doc.createtextnode(lastname));             contact.appendchild(lastname);             element pn = doc.createelement("phonenumber");             pn.appendchild(doc.createtextnode(java.lang.long.tostring(phonenumber)));             contact.appendchild(pn);          }         /**         *         * function writetoxmlfile responsible writing data output xml file "phonebook.xml".         * writetoxmlfile formats data written pretty print way indent spaces , line breaks etc.         */         void writetoxmlfile(){             try                  {                 transformer.setoutputproperty(outputkeys.indent, "yes");                 transformer.setoutputproperty("{http://xml.apache.org/xslt}indent-amount", "2");                 source = new domsource(doc);                 result = new streamresult(new file(filepathstring));                 transformer.transform(source, result);                 system.out.println("contact saved !");                 }             catch (transformerexception tfe)                  {                     tfe.printstacktrace();                  }         }         /**         *         * function updatexmlfile updates existing xml file new user data.         * new set of user data gets unique id element "contact" calculated , generated updatexmlfile.         *          */         void updatexmlfile(){             try             {                 doc = docbuilder.parse(filepathstring);             }catch(saxexception sae){              }catch (ioexception ioe) {             ioe.printstacktrace();         }              int attrvalue=1;             node contactinfo = doc.getfirstchild();             nodelist numberchildnodes = contactinfo.getchildnodes();             for(int i=0;i<numberchildnodes.getlength();i++)                 {                                 node n = numberchildnodes.item(i);                     if ("contact".equals(n.getnodename()))                          {                             attrvalue+=1;                         }                      }                     element contact = doc.createelement("contact");         contactinfo.appendchild(contact);             attr attr = doc.createattribute("id");             attr.setvalue(integer.tostring(attrvalue));             contact.setattributenode(attr);             element firstname = doc.createelement("firstname");             firstname.appendchild(doc.createtextnode(firstname));             contact.appendchild(firstname);             element lastname = doc.createelement("lastname");             lastname.appendchild(doc.createtextnode(lastname));             contact.appendchild(lastname);             element pn = doc.createelement("phonenumber");             pn.appendchild(doc.createtextnode(java.lang.long.tostring(phonenumber)));             contact.appendchild(pn);          }     } 

the above code first version of xmlphonebook , working fine :

c:\users\xxxxxx\documents\java\xml>java xmlphonebook enter firstname = xxxxxx enter lastname = yyyyyy enter phonenumber = 789634569863 contact saved ! 

my problem started when tried update above code error handling class show below.

main class xmlphonebook gets exceptions:

    /**      *      * @author sanjayan ravi      */     package xmlphonebook;     /**      *      * class xmlphonebook main class controls getcontactinfo function , storecontactinfo.      */     public class xmlphonebook      {         getcontactinformation gci;         storecontactinformation sci;           xmlphonebook()         {             gci = new getcontactinformation();          }         /**         *         * getcontactinfo function triggers functions getfirstname, getlastname, getphonenumber of getcontactinformation class.         */         void getcontactinfo()throws exception {                     gci.getfirstname();             gci.getlastname();             gci.getphonenumber();         }         /**         *         * variables fname, lname, phonenumber of class getcontactinformation contains user entered data, these values passed class storecontactinformation creating/updating xml file user data.         */         void storecontactinfo()throws exception{                          sci = new storecontactinformation(gci.fname,gci.lname,gci.phonenumber);                        }          public static void main(string[] args)          {             xmlphonebook pb = new xmlphonebook();             try{             pb.getcontactinfo();             pb.storecontactinfo();             }catch(exception e){                 errorhandler er = new errorhandler(e);             }         }      } 

class getcontactinformation :

    package xmlphonebook;     /**     *     * class getcontactinformation responsible getting inputs user such first name, last name , phone number.      * variables fname(string), lname(string), phonenumber(long) used containing user data during run time.     * variable reader(scanner) used getting inputs user via console.     */     import java.util.scanner;      public class getcontactinformation {         string fname;         string lname;         long phonenumber;         scanner reader;          getcontactinformation(){             fname=null;             lname=null;             phonenumber=0;         }         /**          *          * function getfirstname prompts user first name , gets inputs console.          * value first name passed function setfirstname.          */         void getfirstname()throws exception{             system.out.println("enter firstname = ");             reader = new scanner(system.in);             setfirstname(reader.nextline());         }          /**          *          * function getlastname prompts user last name , gets inputs console.          * value last name passed function setlastname.          */         void getlastname()throws exception{             system.out.println("enter lastname = ");             reader = new scanner(system.in);             setlastname(reader.nextline());         }          /**          *          * function getphonenumber prompts user phone number , gets inputs console.          * value phone number passed function setphonenumber.          */         void getphonenumber()throws exception{              system.out.println("enter phonenumber = ");             reader = new scanner(system.in);               setphonenumber(long.parseunsignedlong(reader.nextline()));          }         /**          *          * function setfirstname assigns value receives variable fname.          */         string setfirstname(string fn)throws exception{            return  fname=fn;         }         /**          *          * function setlastname assigns value receives variable lname.          */         string setlastname(string ln)throws exception{             return  lname=ln;         }          /**          *          * function setphonenumber assigns value receives variable phonenumber.          */         long setphonenumber(long pn)throws exception{             return  phonenumber=pn;         }     } 

class storecontactinformation :

    package xmlphonebook;     /**      *      * storecontactinformation responsible storing user data such first name, last name , phone number xml file called phonebook.xml.      * storecontactinformation first checks if xml file exist if file exist updates file or else creates new xml file provided user data.      *      */     import java.io.file;     import javax.xml.parsers.documentbuilder;     import javax.xml.parsers.documentbuilderfactory;     import javax.xml.transform.transformer;     import javax.xml.transform.transformerfactory;     import javax.xml.transform.dom.domsource;     import javax.xml.transform.stream.streamresult;     import javax.xml.transform.outputkeys;     import javax.xml.transform.transformerexception;      import org.w3c.dom.attr;     import org.w3c.dom.document;     import org.w3c.dom.element;      import java.util.scanner;     import org.w3c.dom.node;     import org.w3c.dom.nodelist;       public class storecontactinformation {          file f;         string filepathstring ;         documentbuilderfactory docfactory ;         documentbuilder docbuilder ;         document doc;         transformerfactory transformerfactory;         transformer transformer;         domsource source;         streamresult result;         string firstname;         string lastname;         long phonenumber;         int choice;         scanner reader;         outputkeys outputkeys;          storecontactinformation(string fn, string ln, long pn) throws exception {              filepathstring="phonebook.xml"; //file path current working directory.              f = new file(filepathstring);             firstname=fn;             lastname=ln;             phonenumber=pn;             docfactory = documentbuilderfactory.newinstance();             docbuilder = docfactory.newdocumentbuilder();             transformerfactory = transformerfactory.newinstance();              // check if xml file exist !                     if(f.exists() && !f.isdirectory()) {                 //if exist                 updatexmlfile();                 writetoxmlfile();              }else{                 //if not exist                 createxmlfile();                  writetoxmlfile();             }            }         /**         *         * function createxmlfile creates new xml file if 1 doesn't exist already.          * first set of data stored in xml file given unique id="1".         * root element of xml file "contactinformation" contains child nodes "contact" there unique ids.         * element "contact further contains child nodes "firstname","lastname" , "phonenumber".         */         void createxmlfile(){              doc = docbuilder.newdocument();             element rootelement = doc.createelement("contactinformation");             doc.appendchild(rootelement);             element contact = doc.createelement("contact");             rootelement.appendchild(contact);             attr attr = doc.createattribute("id");             attr.setvalue("1");             contact.setattributenode(attr);             element firstname = doc.createelement("firstname");             firstname.appendchild(doc.createtextnode(firstname));             contact.appendchild(firstname);             element lastname = doc.createelement("lastname");             lastname.appendchild(doc.createtextnode(lastname));             contact.appendchild(lastname);             element pn = doc.createelement("phonenumber");             pn.appendchild(doc.createtextnode(java.lang.long.tostring(phonenumber)));             contact.appendchild(pn);          }         /**         *         * function writetoxmlfile responsible writing data output xml file "phonebook.xml".         * writetoxmlfile formats data written pretty print way indent spaces , line breaks etc.         */         void writetoxmlfile() throws exception{              transformer.setoutputproperty(outputkeys.indent, "yes");             transformer.setoutputproperty("{http://xml.apache.org/xslt}indent-amount", "2");             source = new domsource(doc);             result = new streamresult(new file(filepathstring));             transformer.transform(source, result);             system.out.println("contact saved !");          }         /**         *         * function updatexmlfile updates existing xml file new user data.         * new set of user data gets unique id element "contact" calculated , generated updatexmlfile.         *          */         void updatexmlfile() throws exception{              doc = docbuilder.parse(filepathstring);             int attrvalue=1;             node contactinfo = doc.getfirstchild();             nodelist numberchildnodes = contactinfo.getchildnodes();             for(int i=0;i<numberchildnodes.getlength();i++)                 {                                 node n = numberchildnodes.item(i);                     if ("contact".equals(n.getnodename()))                          {                             attrvalue+=1;                         }                      }                  element contact = doc.createelement("contact");             contactinfo.appendchild(contact);             attr attr = doc.createattribute("id");             attr.setvalue(integer.tostring(attrvalue));             contact.setattributenode(attr);             element firstname = doc.createelement("firstname");             firstname.appendchild(doc.createtextnode(firstname));             contact.appendchild(firstname);             element lastname = doc.createelement("lastname");             lastname.appendchild(doc.createtextnode(lastname));             contact.appendchild(lastname);             element pn = doc.createelement("phonenumber");             pn.appendchild(doc.createtextnode(java.lang.long.tostring(phonenumber)));             contact.appendchild(pn);          }       } 

class errorhandler :

    package xmlphonebook;      import javax.xml.parsers.parserconfigurationexception;     import java.lang.numberformatexception;     import javax.xml.transform.transformerexception;      import org.xml.sax.saxexception;     import java.io.ioexception;      public class errorhandler extends exception{          errorhandler(exception e){              if(e.tostring().contains("numberformatexception"))             {   system.out.println("enter information corractly");             }else if(e.tostring().contains("parserconfigurationexception"))             {   system.out.println("doc builder error");                   e.printstacktrace();             }else if(e.tostring().contains("transformerexception"))             {   system.out.println("transformation error between source , result ");                  e.printstacktrace();             }else if(e.tostring().contains("saxexception"))             {   system.out.println("doc builder error in updatexmlfile function");                  e.printstacktrace();             }else if(e.tostring().contains("ioexception"))             {   system.out.println("io exception error");                  e.printstacktrace();             }else{                 e.printstacktrace();             }                }     } 

output :

enter firstname =  xxxxxxxx enter lastname =  yyyyyyyy enter phonenumber =  7896456123693 

error :

java.lang.nullpointerexception @ xmlphonebook.storecontactinformation.writetoxmlfile(storecontactinformation.java:105) @ xmlphonebook.storecontactinformation.<init>(storecontactinformation.java:65) @ xmlphonebook.xmlphonebook.storecontactinfo(xmlphonebook.java:35) @ xmlphonebook.xmlphonebook.main(xmlphonebook.java:43) 

function causes error:

 void writetoxmlfile() throws exception{          transformer.setoutputproperty(outputkeys.indent, "yes");         transformer.setoutputproperty("{http://xml.apache.org/xslt}indent-amount", "2");         source = new domsource(doc);         result = new streamresult(new file(filepathstring));         transformer.transform(source, result);         system.out.println("contact saved !");      } 

please tell me mistake doing.

i copied classes in workspace, , indeed there npe, mentioned in 1 of previous comments, transformer.setoutputproperty(outputkeys.indent, "yes"); transformer null, checked out debugging , keeping break point , used same solution fix mentioned in comment.

this how resolved it, in constructor

    storecontactinformation(string fn, string ln, long pn) throws exception {         filepathstring="phonebook.xml"; //file path current working directory.          f = new file(filepathstring);         firstname=fn;         lastname=ln;         phonenumber=pn;         docfactory = documentbuilderfactory.newinstance();         docbuilder = docfactory.newdocumentbuilder();         transformerfactory = transformerfactory.newinstance();          /******* added line ******************/         transformer=transformerfactory.newtransformer();          /******* added line ******************/          // check if xml file exist !                 if(f.exists() && !f.isdirectory()) {             //if exist             updatexmlfile();             writetoxmlfile();          }else{             //if not exist             createxmlfile();              writetoxmlfile();         }      } 

and got output,

enter firstname = xxxx

enter lastname = yyyy

enter phonenumber = 123456

contact saved !


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -