Tobe
Tobe

Reputation: 93

Java Vaadin: CSV to Grid

I have a CSV File which I want to display in a Grid in Vaadin. The File looks like this:

CTI.csv

Facebook
Twitter
Instagram
Wiki

So far i tried it with a while Loop and a for Loop. The for Loop looks like this:

Scanner sc = null;
    try {
        sc = new Scanner(new File("C:/development/code/HelloWorld/src/CTI.csv"));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
List<CTITools> tools = null;
for (Iterator<String> s = sc; s.hasNext(); ) {
    tools = Arrays.asList(new CTITools(s.next()));
}

Grid<CTITools> grid = new Grid<>();
grid.setItems(tools);
grid.addColumn(CTITools::getTool).setCaption("Tool");
layout.addComponents(grid);

setContent(layout);

The issue now is that it only shows the last entry "Wiki". If i hardcode the data like the following it works:

List<CTITools> tools;
tools = Arrays.asList(
            new CTITools("DFC"),
            new CTITools("AgentInfo"),
            new CTITools("Customer"));
            new CTITools("Wiki"));

Grid<CTITools> grid = new Grid<>();
grid.setItems(tools);
grid.addColumn(CTITools::getTool).setCaption("Tool");

So what am I doing wrong? Why doesn't the Loop work?

Upvotes: 0

Views: 224

Answers (2)

C.Champagne
C.Champagne

Reputation: 5489

You create a new list at each iteration so you lose your previous content.

tools = Arrays.asList(new CTITools(s.next()));

You should only add items to the same tools list

List<CTITools> tools = new ArrayList<>();
for (Iterator<String> s = sc; s.hasNext(); ) {
    tools.add(new CTITools(s.next()));
}

Upvotes: 1

muzychuk
muzychuk

Reputation: 298

The line tools = Arrays.asList(new CTITools(s.next())); creates new list on each iteration. If you want your items to be stored in one list you need to create it once. Then use tools.add(new CTITools(s.next())) to add the items to the same list in the loop.

Upvotes: 2

Related Questions