Java Forums

Main Menu
Home
Today's Posts
FAQ
Search
Contact Us

Java Network
Java Tips
Java Tips Blog

Sponsored Links





Welcome to the Java Forums.

You are currently viewing our boards as a guest which gives you limited access to view most discussions and access our other features. By joining our free community, you will:

  • have access to post topics
  • communicate privately with other members (PM)
  • not see advertisements between posts
  • have the possibility to earn one of our surprises if you are an active member
  • access many other special features that will be introduced later.

Registration is fast, simple and absolutely free so please, join our community today!

If you have any problems with the registration process or your account login, please contact us.

Reply
 
LinkBack Thread Tools Display Modes
  #1 (permalink)  
Old 06-14-2008, 10:45 PM
Member
 
Join Date: Jun 2008
Posts: 1
Zuela is on a distinguished road
[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:

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; }

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.
Bookmark Post in Technorati
Reply With Quote
Sponsored Links
  #2 (permalink)  
Old 06-16-2008, 12:51 PM
Senior Member
 
Join Date: Jun 2008
Posts: 181
masijade is on a distinguished road
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.

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);
Bookmark Post in Technorati
Reply With Quote
Sponsored Links
Reply


Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


Similar Threads
Thread Thread Starter Forum Replies Last Post
Java Project Trouble: Searching one ArrayList with another ArrayList BC2210 New To Java 2 04-21-2008 12:43 PM
ArrayList ramitmehra123 New To Java 1 02-07-2008 01:47 AM
ArrayList kizilbas1 New To Java 1 01-12-2008 09:48 PM
ArrayList kizilbas1 New To Java 11 12-05-2007 08:30 PM
New to arraylist kleave New To Java 2 11-19-2007 07:45 PM


All times are GMT +3. The time now is 06:44 PM.


VBulletin, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Content Relevant URLs by vBSEO ©2007, Crawlability, Inc.
Copyright ©2006 - 2007, www.java-forums.org