Help with Arraylist

Asked

Viewed 129 times

1

Only the last two elements of my Arraylist are sent as datasource in ireport. I have an Arraylist that stores read tag data in 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 fills an Arraylist, but when I send to ireport only the last two data that are of the last xml are displayed.

Code that allows the selection of 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 generating the 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 does the report: Apenas os 2 valores do arquivo3.xml são listados

And finally that’s what’s shown on Saida: Resultado do System.out.println("Nome no Arquivo xml: "+c.getNome());

Thank you guys.

  • 1

    if I may, I would like to add an addendum on Arraylist: here

1 answer

1


The problem

By logging out 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 you have a loop for which generates a report for each item in the list.

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

The biggest problem is that each time the generation method is executed it overwrites those that were previously generated. Understands?

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 in a single list.

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

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

Solution: Multiple Reports

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

In the meantime, remove the for from within the report generation method. Add a counter as a method parameter 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 run is different from the previous one.

  • 1

    Thank you very much, with your explanation things have become clearer.

  • Excellent! And welcome to [en.so]!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.