0

I use Vaadin framework v23 for my project.

A wanted to add a component column to one of my Grids, a number field. My Grid's rows are representing an entity from the database my program connected to. I ask for an input from the user, and I want to write that input back to the DB. I found this solution at several sites:

private Grid<Honey> initHoneyGrid() {
    Grid<Honey> honeyGrid = new Grid<>(Honey.class);

    honeyGrid.setItems(honeys);
    honeyGrid.removeColumnByKey("id");
    honeyGrid.removeColumnByKey("quantityPacked");
    honeyGrid.removeColumnByKey("flatCost");
    honeyGrid.removeColumnByKey("sellingPrice");
    honeyGrid.setColumns("kindOfHoney", "weight", "quantityBack");

    honeyGrid.addComponentColumn(item -> new NumberField("Set the quantity you brought back'", event -> {
        item.setQuantityBack(event.getValue().intValue());
        honeyService.updateHoney(item);
        honeyGrid.getDataProvider().refreshAll();
    }));

    return honeyGrid;
}

However, the variable "item" throws NullPointerException. The "honeys" variable is an ArrayList, which is filled from the DB directly. I use Spring Boot JPA to access the database. How can I avoid it?

Vikrant Kashyap
  • 6,398
  • 3
  • 32
  • 52
  • Are you sure `item` is null? Maybe it's `event.getValue()`? – Frettman May 13 '22 at 23:05
  • f.y.i. you can avoid having to remove unncessessary columns by initializing the grid like this `new Grid<>(Honey.class, false)` – kscherrer May 19 '22 at 15:24
  • Thank you for the Grid initialization tip! Actually the problem was a Hibernate lazy initialization problem. The honeys List was not filled from the DB properly. I solved it, and my code works just fine. – Márton Szabó May 21 '22 at 18:29

1 Answers1

1

check docs here to see components and usage of them, the reason of NPE that you get is item might not be initialised, what you are trying to do now is assign some property that you don't have any value of it in item to new NumberField(...)

the lambda expression will already assign new NumberField(...) to ìtem at the end

Mohammed Fataka
  • 150
  • 1
  • 8
  • 1
    The root problem was Hibernate Lazy initialization, that was why the item was null. Solving it solved the Grid problem as well. But the link you sent me is quite useful, thank you! – Márton Szabó May 21 '22 at 18:32