Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 6 of 6

Thread: Java XML: IndexOutOfBoundsException When appending a node

  1. #1
    Junior Member
    Join Date
    May 2013
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Java XML: IndexOutOfBoundsException When appending a node

    Java XML: IndexOutOfBoundsException When appending a node

    Dear all,

    Now that I am writing a messenger program. The following code shall store the message history.
    Sadly, I've encountered an "IndexOutOfBounds" exception on a line and I've been trying for a whole day,
    but still can't figure out the problem.

    So here it is.

    	public static final SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	public static final String FILE_PATH = "/data/data/com.demo.xmppchat/";
    	public static Map<Date, String> messagesMap = new TreeMap<Date, String>();
     
    	// File should be saved as /username/buddy.xml
    	public static void writeHistory(String username, String buddy, Map<Date, String> messages)
    	{
    		try {			
     
    			// Check if the file exists. If the file does not exist, create and initiate one. 
    			File file = new File(FILE_PATH + username);
    			if (!file.exists()) {
    				file.mkdirs();
    			}	
    			file = new File(FILE_PATH + username + "/" + buddy + ".xml");
    			// file.setReadable(true); file.setWritable(true); file.setExecutable(true);
    			if (!file.exists()) {
    				file.createNewFile();				
    				initiateHistoryFile(username, buddy);
    			}
     
    			// Now that the XML file should exists as we have created and initialized one.
     
    			// TODO:
    			// Now we modify the XML file
     
    			DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    			DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    			Document doc = docBuilder.parse(file);
    			Element root = doc.getDocumentElement();
    			Element rootE = doc.getDocumentElement();	
    			String s = "";
    			Node n = null;
     
    			for (Map.Entry<Date, String> entry : messages.entrySet()) {		
     
    				// <message>
    				Element messageE = doc.createElement("message");
    				rootE.appendChild(messageE);
     
    				// Set attribute to <message> element
    				// messageE.setAttribute("id", "1");
     
    				// <from>
    				Element fromE = doc.createElement("from");
    				fromE.appendChild(doc.createTextNode(buddy));
    				messageE.appendChild(fromE);
     
    				// <date>
    				Element dateE = doc.createElement("date");
    				s = SDF.format(entry.getKey());
    				n = doc.createTextNode(s);
    				dateE.appendChild(n);
    				messageE.appendChild(dateE);
     
    				// <text>
    				Element textE = doc.createElement("text");
    				s = entry.getValue();
    				n = doc.createTextNode(s);
    				textE.appendChild(n);
    				messageE.appendChild(textE);	
     
    				root.appendChild(messageE); // <- *** THIS IS WHERE "IndexOutOfBounds" exception OCCURS! ***
    			}
     
    			TransformerFactory transformerFactory = TransformerFactory.newInstance();
    			Transformer transformer = transformerFactory.newTransformer();
    			DOMSource source = new DOMSource(doc);
    			StreamResult result = new StreamResult(file);
    			transformer.transform(source, result);
     
    			// Write the file
    			// FileWriter fileWritter = new FileWriter(file.getName(),true);
    	        // BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
    	        // bufferWritter.write("");
    	        // bufferWritter.close();		
     
    		} catch (Exception e) {
    			ToneGenerator toneGenerator = new ToneGenerator(AudioManager.STREAM_SYSTEM, ToneGenerator.MAX_VOLUME);
    			toneGenerator.startTone(ToneGenerator.TONE_PROP_BEEP);
    			e.printStackTrace();
    		}
    	}

    Thank you so much for your help.

    --- Update ---

    W/System.err(1067): java.lang.IndexOutOfBoundsException: Invalid index 1, size is 0
    W/System.err(1067): at java.util.ArrayList.throwIndexOutOfBoundsException (ArrayList.java:251)
    W/System.err(1067): at java.util.ArrayList.add(ArrayList.java:143)
    W/System.err(1067): at org.apache.harmony.xml.dom.InnerNodeImpl.insertChi ldAt(InnerNodeImpl.java:126)
    W/System.err(1067): at org.apache.harmony.xml.dom.InnerNodeImpl.appendChi ld(InnerNodeImpl.java:52)
    W/System.err(1067): at com.demo.xmppchat.XMLReadWrite.writeHistory(XMLRea dWrite.java:113)


  2. #2
    Grand Poobah
    Join Date
    Mar 2011
    Posts
    1,465
    My Mood
    Grumpy
    Thanks
    0
    Thanked 158 Times in 149 Posts

    Default Re: Java XML: IndexOutOfBoundsException When appending a node

    Did you bother to read the error message? It says that you are trying to access the array with an index of 1. It is illegal because the size of the array is 0 which makes it totally useless. Go to the line generating the error, find out what the array is, go to the creation of the array and find out why it is 0. Are you getting the array from some external source? If so perhaps you should investigate why it is sending you a 0 length array or maybe use an if statement to see if the array has any data in it before trying to do anything with it.
    Improving the world one idiot at a time!

  3. #3
    Junior Member
    Join Date
    Nov 2011
    Location
    Aarhus, Denmark
    Posts
    28
    Thanks
    0
    Thanked 1 Time in 1 Post

    Default

    You are appending messageE to the root element twice, first to rootE and then later to root. both which point to the same document root. This might be where the exception is thrown.

  4. #4
    Junior Member
    Join Date
    May 2013
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Java XML: IndexOutOfBoundsException When appending a node

    Quote Originally Posted by rolfba View Post
    You are appending messageE to the root element twice, first to rootE and then later to root. both which point to the same document root. This might be where the exception is thrown.
    Thank you all, and yes, the problem is here. I have removed
    rootE.appendChild(messageE);
    and it works.

  5. #5
    Member
    Join Date
    May 2011
    Location
    west palm beach, FL
    Posts
    189
    My Mood
    Tired
    Thanks
    41
    Thanked 11 Times in 10 Posts

    Default Re: Java XML: IndexOutOfBoundsException When appending a node

    thats why i love java better than c++! it tells you when you go outside of your arrays

  6. #6
    Junior Member
    Join Date
    May 2013
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Java XML: IndexOutOfBoundsException When appending a node

    Quote Originally Posted by derekxec View Post
    thats why i love java better than c++! it tells you when you go outside of your arrays
    Yes! You're right. This program will probably crash if i'm writing it in C++

Similar Threads

  1. Wireless sensor node in java
    By jeniferrubys in forum What's Wrong With My Code?
    Replies: 1
    Last Post: May 28th, 2013, 02:28 AM
  2. [SOLVED] XML get/set node by attribute value
    By b_jones10634 in forum File I/O & Other I/O Streams
    Replies: 1
    Last Post: August 24th, 2010, 11:26 AM
  3. Java Newbie: How to Code Node and its Neighbors?
    By ke3pup in forum Java Theory & Questions
    Replies: 0
    Last Post: April 20th, 2010, 01:00 AM
  4. Xml-Node Retrieval
    By prasb in forum File I/O & Other I/O Streams
    Replies: 0
    Last Post: December 4th, 2009, 11:44 AM
  5. java xml-rpc response parsing to xml
    By kievari in forum File I/O & Other I/O Streams
    Replies: 0
    Last Post: November 19th, 2009, 01:36 PM

Tags for this Thread