Help with ArrayList

1

Only the last two elements of my Arraylist are sent as datasource in ireport. I have an ArrayList that stores read data from tags into xml files. For example, I select three xml files with the same tags but with different data. I have a method that reads these files and is filling an ArrayList, but when I send pro ireport only the last two data that are of the last xml are displayed.

Code that allows the selection of the files and sends them to read, after reading a list is returned and I pass the list as datasource:

  private void btnPegarArquivoActionPerformed(java.awt.event.ActionEvent evt) {                                                
    // TODO add your handling code here:
    JFileChooser chooser = new JFileChooser();
    // Possibilita a seleção de vários arquivos
    chooser.setMultiSelectionEnabled(true);

    // Apresenta a caixa de diálogo
    chooser.showOpenDialog(null);

    // Retorna os arquivos selecionados. Este método retorna vazio se
    // o modo de múltipla seleção de arquivos não estiver ativada.
    File[] files = chooser.getSelectedFiles();

    for (File argumento : files) {
       System.err.println("Argumentos: " + argumento.getPath());
        caminho = argumento.getPath();
        LeitorXMLDOMMelhorado parser = new LeitorXMLDOMMelhorado();

        try {
            /* List<Cliente> */
            listaContatos = (ArrayList<Cliente>) parser.realizaLeituraXML(caminho);
            System.out.println("Valores: " + listaContatos);


            for(Cliente c : listaContatos){ 
                System.out.println("Nome no Arquivo xml: "+c.getNome());
                gerarRelatorio((ArrayList) listaContatos);
            } 
        } catch (ParserConfigurationException e) {
            System.out.println("O parser não foi configurado corretamente.");
            e.printStackTrace();
        } catch (SAXException e) {
            System.out.println("Problema ao fazer o parse do arquivo.");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("O arquivo não pode ser lido.");
            e.printStackTrace();
        }

    }


}               

Method that generates report:

 public void gerarRelatorio(ArrayList list) {
    for (int i = 0; i < lista.size(); i++) {

        JasperReport report = null;

        try {
            InputStream inputStreamReal = getClass().getResourceAsStream("/br/com/testexml/relatorio/Teste.jrxml");
            report = JasperCompileManager.compileReport(inputStreamReal);

        } catch (JRException ex) {
            Logger.getLogger(TesteView.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            JasperPrint print = JasperFillManager.fillReport(report, null, new JRBeanCollectionDataSource(list));
            JasperExportManager.exportReportToPdfFile(print,
                    "C:\relatorios/RelatorioClientes" + i + ".pdf");

        } catch (JRException ex) {
            Logger.getLogger(TesteView.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}

Class that reads xml and fills a list:

public class LeitorXMLDOMMelhorado {

public List<Cliente> realizaLeituraXML(String arquivoXML) throws ParserConfigurationException, SAXException, IOException {
    //fazer o parse do arquivo e criar o documento XML
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(arquivoXML);

    //Passo 1: obter o elemento raiz
    Element raiz = doc.getDocumentElement();
    System.out.println("O elemento raiz é: " + raiz.getNodeName());

    //Passo 2: localizar os elementos filhos da agenda
    NodeList listaContatos = raiz.getElementsByTagName("contato");

    List<Cliente> lista = new ArrayList<Cliente>(listaContatos.getLength());

    //Passo 3: obter os elementos de cada elemento contato
    for (int i = 0; i < listaContatos.getLength(); i++) {

        //como cada elemento do NodeList é um nó, precisamos fazer o cast
        Element elementoContato = (Element) listaContatos.item(i);

        //cria um objeto Contato com as informações do elemento contato
        Cliente contato = criaContato(elementoContato);
        lista.add(contato);
        //System.err.println("Listaaaaaaa: " + lista);

        // System.err.println("Lista no metodo:"+lista);
    }

    return lista;
}

public String obterValorElemento(Element elemento, String nomeElemento) {
    //obtém a lista de elementos
    NodeList listaElemento = elemento.getElementsByTagName(nomeElemento);
    if (listaElemento == null) {
        return null;
    }
    //obtém o elemento
    Element noElemento = (Element) listaElemento.item(0);
    if (noElemento == null) {
        return null;
    }
    //obtém o nó com a informação
    Node no = noElemento.getFirstChild();
    return no.getNodeValue();
}

public Cliente criaContato(Element elemento) {
    Cliente contato = new Cliente();
    contato.setCod(Integer.parseInt(elemento.getAttributeNode("id").getNodeValue()));
    contato.setNome(obterValorElemento(elemento, "nome"));
    contato.setProduto(obterValorElemento(elemento, "produto"));
    contato.setCpf(obterValorElemento(elemento, "cpf"));
    contato.setValorCompra(Float.parseFloat(obterValorElemento(elemento, "valor")));

    return contato;
}

}

How the report looks:

AndfinallythisiswhatisdisplayedintheOutput:

asked by anonymous 14.04.2015 / 13:33

1 answer

1

The problem

By log output you can see that you are reading 3 XMLs, each with two clients.

In the program, you call the generation routine three times and within that routine there is a for loop that generates a report for each item in the list.

At the end of the day, you're generating the report 6 times. Twice for the first two customers, twice with the middle two and twice for the last two.

The biggest problem is that every time the generation method runs, it overrides the ones that were generated earlier. Do you understand?

Solution: Single Report

If the goal is to generate a single report with all clients, you need to read the XMLs first and add the results to a single list.

For example, create another list in the main method and add the list items returned from reading each XML using the addAll method.

Only then call the method to generate the report and do the generation only once.

Solution: Multiple Reports

If the goal is to generate a report for each XML, then the code is almost correct.

However, remove for from within the report generation method. Add as a method parameter a counter that will be used in the file name. Finally, when calling this method, pass a different value for each generation, so that the name of the file generated in each execution is different from the previous one.

    
14.04.2015 / 17:33