I have created a blank .xml file on the SD card, and now I’m trying to open it for parsing.
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document newDoc = docBuilder.parse(xmlFile);
When it reaches the parse() method I get the following logcat:
03-11 12:07:20.676: E/Exception(18774): org.xml.sax.SAXParseException: Unexpected end of document
03-11 12:07:20.676: E/Exception(18774): at org.apache.harmony.xml.parsers.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:131)
03-11 12:07:20.676: E/Exception(18774): at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:186)
03-11 12:07:20.676: E/Exception(18774): at mfc.generalguixapi8.SaveData4.saveData(SaveData4.java:76)
03-11 12:07:20.676: E/Exception(18774): at mfc.generalguixapi8.SaveData4.onCreate(SaveData4.java:40)
03-11 12:07:20.676: E/Exception(18774): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
03-11 12:07:20.676: E/Exception(18774): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
03-11 12:07:20.676: E/Exception(18774): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
03-11 12:07:20.676: E/Exception(18774): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
03-11 12:07:20.676: E/Exception(18774): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
03-11 12:07:20.676: E/Exception(18774): at android.os.Handler.dispatchMessage(Handler.java:99)
03-11 12:07:20.676: E/Exception(18774): at android.os.Looper.loop(Looper.java:123)
03-11 12:07:20.676: E/Exception(18774): at android.app.ActivityThread.main(ActivityThread.java:4627)
03-11 12:07:20.676: E/Exception(18774): at java.lang.reflect.Method.invokeNative(Native Method)
03-11 12:07:20.676: E/Exception(18774): at java.lang.reflect.Method.invoke(Method.java:521)
03-11 12:07:20.676: E/Exception(18774): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
03-11 12:07:20.676: E/Exception(18774): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
03-11 12:07:20.676: E/Exception(18774): at dalvik.system.NativeStart.main(Native Method)
The exception is thrown because a blank file isn’t considered a valid XML file by the parser. To be able to create, change and parse XML files dynamically, you need to make sure that your file is always valid. To make it valid from the start you should consider putting in just a root tag, and then add the information inside it – this way you won’t get into trouble parsing the file.