Results 1 to 2 of 2
  1. #1
    Zuela is offline Member
    Join Date
    Jun 2008
    Posts
    1
    Rep Power
    0

    Default [Problems] ArrayList

    Hello to all, well i'm a new user and i have a problem with ArrayList.

    Well i need to get some information from a log in xml and save it in a DB; i create
    a method wich will return a ArrayList of the type message; but for some reason the final ArrayList that i get is just the last element wich is repeating a lot of times.

    Well the code is:

    Java Code:
    //Obtem os dados do log
    	public ArrayList<Message> getDados(File arquivo)  throws ParserConfigurationException, SAXException,IOException, XPathExpressionException 
        {
    
    		
    		
    		Message message = new Message();
    		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    		factory.setNamespaceAware(true); // never forget this!
    		DocumentBuilder builder = factory.newDocumentBuilder();
    		Document doc = builder.parse(arquivo);
    			
    		
    		NodeList bodys = doc.getElementsByTagName("body");
    		
    		ArrayList<Message> messages = new ArrayList<Message>();
    		
    		
    		for (int i = 0; i < bodys.getLength(); i++) 
    		{
    			Node nodeBody = bodys.item(i); 
    			
    			//Extrai o texto do no Body
    			/*if (nodeBody.hasChildNodes())
    			{
    				message.setMessage(nodeBody.getFirstChild().getTextContent().toString());	
    			}
    			else
    			{*/
    				message.setMessage(nodeBody.getTextContent().toString());				
    			//}
    			
    			//Extrai os atributos do "message" pai do no body corrente
    			Attr attr;
    			Node nodeMessage = nodeBody.getParentNode();
    			for (int j=0; j < nodeMessage.getAttributes().getLength();j++)
    			{
    				attr = (Attr)nodeMessage.getAttributes().item(j);
    				if (attr.getName()=="to")
    				{
    					message.setTo(attr.getValue());
    				}
    				else if (attr.getName()=="from")
    				{
    					message.setFrom(attr.getValue());
    				}
    				else if (attr.getName()=="type")
    				{
    					message.setType(attr.getValue());
    				}
    				else if (attr.getName()=="id")
    				{
    					message.setId(attr.getValue());
    				}	
    			}
    			//Extrai os atributos do "packet" avo do no body corrente
    			Node nodePacket = nodeMessage.getParentNode();
    			for (int j=0; j < nodePacket.getAttributes().getLength();j++)
    			{
    				attr = (Attr)nodePacket.getAttributes().item(j);
    				if (attr.getName()=="timestamp")
    				{
    					message.setTimeStamp(attr.getValue());
    				}
    			}
    			messages.add(message);
    			
    		}
    		
    		return messages;
    	}

    Java Code:
    public static void  main(String[] args) throws Exception 
    	{
    		Connection connection   = null;//gerencia conexão
    		PreparedStatement stmt  = null;//instrução de consulta
    		
    		//O diretorio dos logs
    		String urlDiretorio = "C:/Java/log xml/conversas";
    		File diretorio  = new File(urlDiretorio);
    		
    		//Arquivos no diretorio
    		String arquivos[] = diretorio.list();
    		
    		File arquivoXml;   
    		Xml xml = new Xml();
    				
    		//conecta-se ao banco de dados e o consulta
    		try
    		{
    			Class.forName( JDBC_DRIVER );//carrega a classe de driver do banco de dados
    			
    			//estabelece conexão com o banco de dados
    			connection = DriverManager.getConnection (DATABASE_URL, "ADMINLOG","ADMIN");
    			
    			//cria Statement para consultar banco de dados
    		    //statement = connection.createStatement();
    			
    		    //cria um preparedStatement  
    			stmt = connection.prepareStatement("INSERT INTO LOG (\"ID\",\"TO\",\"FROM\",\"MESSAGE\",\"TYPE\") VALUES (?,?,?,?,?)");
    		    
    		    
    		    for (int i=0; i < arquivos.length; i++)
    			{
    				arquivoXml = new File(urlDiretorio+"/"+arquivos[i]);
    				if (arquivoXml.isFile())
    				{	
    					String conteudoArquivo = xml.retArq(arquivoXml = new File(urlDiretorio+"/"+arquivos[i]));
    					conteudoArquivo =conteudoArquivo.substring(conteudoArquivo.length()-7);
    					String jive = "</jive>";
    					
    					if (!conteudoArquivo.equalsIgnoreCase(jive))
    						xml.fechaXml(urlDiretorio+"/"+arquivos[i]);
    					
    					ArrayList<Message> messages = new ArrayList<Message>(); 
    					messages   = xml.getDados(arquivoXml = new File(urlDiretorio+"/"+arquivos[i]));
    					
    					for (int j=0;j<messages.size();j++)
    					{
    						System.out.println("Mensagem: "+messages.get(j).getMessage());
    						System.out.println("Id: "+messages.get(j).getId());
    						System.out.println("From: "+messages.get(j).getFrom());	
    						System.out.println("To: "+messages.get(j).getTo());
    						System.out.println("Type: "+messages.get(j).getType());
    						System.out.println(messages.get(j).getTimeStamp());
    						
    						// preenche os valores  
    						stmt.setString(1, messages.get(j).getId());  
    						stmt.setString(2, messages.get(j).getTo());  
    						stmt.setString(3, messages.get(j).getFrom());   
    						stmt.setString(4, messages.get(j).getMessage()); 
    						stmt.setString(5, messages.get(j).getType()); 
    						//executa  
    						//stmt.execute();
    					}	
    					  
    						
    					System.out.println("Gravado!");  
    						
    					
    					
    					
    					File destino = new File (urlDiretorio+"/backups/"+arquivos[i]);
    					//arquivoXml.renameTo(destino);
    				}
    						
    			}
    		     
    		      
    		    
    		}
    		catch ( SQLException sqlException)
    		{
    			sqlException.printStackTrace();
    			System.exit(1);
    		}//fim do catch
    		catch (ClassNotFoundException classNotFound)
    		{
    			classNotFound.printStackTrace();
    			System.exit(1);
    		}//fim do catch
    		finally//asegura que a instrução e a conexão são fechadas adequadamente
    		{
    			try
    			{
    				stmt.close();
    				connection.close();
    			}//fim do try
    			catch ( Exception exception )
    			{
    				exception.printStackTrace();
    				System.exit(1);
    			}//fim do catch
    		}//fim do finally
    	}//fim de main
    Sorry for the horrivell english, i will be improving it slowly.

    I know of the method "getAttribute" but for some reason it doesn't work here.

    If some one can give me an advice for improving my code it will be usefull to, because it's my first java project.

  2. #2
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    9

    Default

    When you store an Object in ana ArrayList, it does not create a copy of that Object and store that, rather it simply stores a copy of the reference value, which will point to the same object as the reference value that was used to store the object. So, when you create one object, store it, then modify it's values, and store it again, you have simply stored the same Object twice. Create a new message object in each iteration rather than simply modifying the values.

    I.E.

    Java Code:
    // bad
    ArrayList<MyObject> a = new ArrayList<MyObject>();
    
    MyObject b = new MyObject();
    b.setID = 1;
    a.store(b);
    b.setID = 2; // This reference is the same one as already stored, so it's value changes to, because it is the same object.
    a.store(b);  // now you have simply stored the same object reference, again.
    
    //good
    ArrayList<MyObject> a = new ArrayList<MyObject>();
    
    MyObject b = new MyObject();
    b.setID = 1;
    a.store(b);
    b = new MyObject();  // now b has a new reference and no longer references the same object as the one already stored in the ArrayList
    b.setID = 2;
    a.store(b);

Similar Threads

  1. Replies: 2
    Last Post: 04-21-2008, 11:43 AM
  2. ArrayList
    By ramitmehra123 in forum New To Java
    Replies: 1
    Last Post: 02-07-2008, 12:47 AM
  3. ArrayList
    By kizilbas1 in forum New To Java
    Replies: 1
    Last Post: 01-12-2008, 08:48 PM
  4. ArrayList
    By kizilbas1 in forum New To Java
    Replies: 11
    Last Post: 12-05-2007, 07:30 PM
  5. New to arraylist
    By kleave in forum New To Java
    Replies: 2
    Last Post: 11-19-2007, 06:45 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •