0

I'm trying to have a dynamic search bar in which you can type and it will update a ListView with the results of the search. What I have so far is a listener on the TextField and a query set to run each time the search bar is modified:

   search.textProperty().addListener((observable, oldValue, newValue) -> {
        TypedQuery<Skill> query = em.createQuery
        ("SELECT p FROM Skill p WHERE p.skill_name LIKE '%" + newValue + "%'", Skill.class);

        lv.getItems().clear();
        skill_list.clear();

        skill_list.addAll(query.getResultList());

        lv.getItems().addAll(skill_list);

    });

The issue with this is that, once any match has been found that is less than the total number of skills in the database (currently 3 for testing), it always displays three skills in the ListView, never any less despite clearing everything and making sure that the results of the query is also just 1. It does find the match, however, and puts it at the top of the ListView without removing any extras which are not even in the queries resultList.

I've tried using separate lists for storing the results and the skills that populate the list before the search bar is used, which changes nothing. How can I make this dynamic search function correctly?

Edit: I am using a CellFactory to display the data in the ListView. That code is as follows:

lv.setCellFactory(param -> new ListCell<Skill>() {
        @Override
        protected void updateItem(Skill skill, boolean empty) {
            super.updateItem(skill, empty);
            if (!empty && skill != null) {
                setText(skill.getName());
                setStyle(null);
            } 
        }
    });
hego64
  • 345
  • 1
  • 5
  • 17
  • 1
    You can do something similar to this [here](https://stackoverflow.com/questions/47559491/making-a-search-bar-in-javafx/47560767#47560767). Basically, get all the relevant data from the database. Then use a `FilteredList` do display what you need from the list. – SedJ601 Aug 03 '18 at 02:58
  • 1
    https://stackoverflow.com/questions/28448851/how-to-use-javafx-filteredlist-in-a-listview – SedJ601 Aug 03 '18 at 03:52
  • 1
    Do you use a custom `cellFactory` for your `ListView`? If this is the case, add the code to the question. – fabian Aug 03 '18 at 06:16
  • 1
    something wrong in the code you are not showing .. ;) the silver bullet is a [mcve] – kleopatra Aug 03 '18 at 07:27
  • Thanks for the responses everyone! @Sedrick, those links both really helped, and cleared things up a bit. And @fabian, I realized that to make my above code work, all I need is an `else` after the `if` in the `CellFactory` to set the text to `null` so it only displays the relevant info. Sometimes it's the little things we miss and need a little shove to figure it out...thanks again everyone. – hego64 Aug 03 '18 at 17:47

0 Answers0