0

I am working on a program that is going to allow users to select/add sounds as favorites via a toggle button with an image in a javafx tableview tablecell and set the status of the sound in the database(the updating of the favorite status in the database works) however the updating of the image only partially works.

when pressing the toggle button the image updates correctly as does the database

initial loading

initial loading output

first 10 records before any favorite selection

enter image description here

after button is pressed

favorite selected

database

enter image description here

but the problem comes when I stop and restart the program because I wind up with none of the buttons selected (sound id 5 should be)

enter image description here

here is the code for the database data loading

public void getSounds() {
        soundFilelist.removeAll(soundFilelist);

        try {
            Connection conn = DriverManager.getConnection("jdbc:sqlite:Sphere.db");
            // add where userId = VerifiedUserId or something simular//
            String sql = "SELECT * FROM Sounds Where userId = ? ";
            PreparedStatement ps;
            ResultSet rs;
            ps = conn.prepareStatement(sql);
            ps.setInt(1 , User.getUserId());
            rs = ps.executeQuery();
            while (rs.next()) {
                int favoriteStatus;
                soundFilelist.add(new Sound(

                        rs.getInt("SoundId") ,
                        rs.getString("SoundName") ,
                        rs.getString("soundPath") ,
                        rs.getLong("soundDurration") ,
                      favoriteStatus = rs.getInt("Favorite")));
                System.out.println(favoriteStatus);
if(favoriteStatus == 0){
    setFavoritesTableButton(0);

}else if(favoriteStatus == 1){
    setFavoritesTableButton(1);

}




                }


                soundBrowser.setItems(soundFilelist);





        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }


    }





                the addButtoncell code

(favorite column 2) modified from https://riptutorial.com/javafx/example/27946/add-button-to-tableview

private void addButtonToTable() {


        Callback<TableColumn<Sound, Void>, TableCell<Sound, Void>> cellFactory = new Callback<TableColumn<Sound, Void>, TableCell<Sound, Void>>() {
            @Override
            public TableCell<Sound, Void> call(final TableColumn<Sound, Void> param) {
                favoritecell = new TableCell<>() {


                    private final ToggleButton btn = new ToggleButton();
                    private Image favoritesImage = new Image("SoundSphere/RegularSizeFavoritesImage.png");
                    private Image favoriteslPressedImage = new Image("SoundSphere/RegularSizeFavoriteslPressedImage.png");
                    private ImageView tableViewFavorites = new ImageView();


                    {


                        tableViewFavorites.setFitWidth(20);
                        tableViewFavorites.setFitHeight(20);
                        btn.setAlignment(Pos.CENTER);
                        // favoritecell.setAlignment(Pos.CENTER);
                        btn.setGraphic(tableViewFavorites);
                        btn.setOnAction((new EventHandler<ActionEvent>() {
                            @Override
                            public void handle(ActionEvent actionEvent) {
                                if ((btn.isSelected())) {
                                    Sound sound = getTableView().getItems().get(getIndex());
                                    sound.setSoundId(soundIdColumn.getCellData(sound));
                                   System.out.println("selected SID:  "+ sound.getSoundId());
                                  int  selectedSoundId2 = sound.getSoundId();
                                    tableViewFavorites.setImage(favoriteslPressedImage);
                                    tableviewFavoriteButtonIsPressed = false;
                                    //addFavorite();
                                    System.out.println("buttonselectedId"+ selectedSoundId);
                                    addFavorite2(selectedSoundId2);

                                }else{

                                    Sound sound = getTableView().getItems().get(getIndex());
                                    sound.setSoundId(soundIdColumn.getCellData(sound));
                                    int  selectedSoundId2 = sound.getSoundId();
                                    tableViewFavorites.setImage(favoritesImage);
                                    tableviewFavoriteButtonIsPressed = true;
                                    removeFavorite2(selectedSoundId2);
                                }

                            }

                            private void removeFavorite2(int selectedSoundId2) {



                                try{

                                    Connection conn = DriverManager.getConnection("jdbc:sqlite:Sphere.db");

                                    String sql = "UPDATE Sounds " +
                                            "SET Favorite = ?"+
//                                            "soundName = ?"+
                                            "Where soundId = ? AND  userId = ?";
                                    PreparedStatement ps;
                                    ps = conn.prepareStatement(sql);
                                    ps.setInt(1,0);
                                    ps.setInt(2 , selectedSoundId2);
                                    ps.setInt(3 , User.getUserId());
                                    ps.executeUpdate();
                                    System.out.println("Data has been removed");



                                }catch(Exception e){
                                    System.out.println("we have a problem with add favorite 2");
                                    e.printStackTrace();
                                }




                            }
                        }));




                            }

                            private void addFavorite2(int favoriteSoundId) {
                                try{

                                    Connection conn = DriverManager.getConnection("jdbc:sqlite:Sphere.db");

                                    String sql = "UPDATE Sounds " +
                                            "SET Favorite = ?"+
//                                            "soundName = ?"+
                                            "Where soundId = ? AND  userId = ?";
                                    PreparedStatement ps;
                                    ps = conn.prepareStatement(sql);
                                    ps.setInt(1,1);
                                    ps.setInt(2 , favoriteSoundId);
                                    System.out.println(favoriteSoundId);
                                    ps.setInt(3 , User.getUserId());
                                    ps.executeUpdate();
                                    System.out.println("Data has been inserted");



                                }catch(Exception e){
                                    System.out.println("we have a problem with add favorite 2");
                                    e.printStackTrace();
                                }




                            }











                    @Override
                    public void updateItem(Void item , boolean empty) {
                        super.updateItem(item , empty);
                        if (btn.isSelected() || dbFavorite) {

                            tableViewFavorites.setImage(tableFavoriteslPressedImage);
                            setGraphic(btn);
                        } if (!btn.isSelected() || !dbFavorite) {
                            tableViewFavorites.setImage(favoritesImage);
                            setGraphic(btn);

                        }
                    }
                };
                return favoritecell;
            }
        };

        favoritesColumn2.setCellFactory(cellFactory);

        soundBrowser.getColumns().add(favoritesColumn2);

    }



public boolean setFavoritesTableButton(int favoriteStatus){
        if(favoriteStatus == 1) {
            dbFavorite  = true;
        }else if(favoriteStatus == 0){
            dbFavorite = false;
        }



    return dbFavorite;
}

relevant Intializable code

soundNameColumn.setCellValueFactory(new PropertyValueFactory<>("soundName"));
        soundPathColumn.setCellValueFactory(new PropertyValueFactory<>("soundPath"));
        soundDurationColumn.setCellValueFactory(new PropertyValueFactory<>("soundDurration"));
        favoritesColumn.setCellValueFactory(new PropertyValueFactory<>("Favorite"));
        addButtonToTable();








        getSounds();

I have tried setting the state of the toggle button in the get sounds method and various Booleans but none of my attempts have worked.

thank you for your time and any help

Thomas Gustafson

  • 1
    Don’t overcomplicate this for yourself or anybody trying to answer. Try to get it working without any database or preference saving. And then ask a question just on that if you get stuck with that part. – jewelsea Jan 29 '22 at 06:04
  • For the database integration, I don’t recommend mixing the data access code with the GUI code, but instead putting some structure into the program using mvc/mvvm and a dao layer, eg [eden coding db connection tutorial](https://edencoding.com/connect-javafx-with-sqlite/). – jewelsea Jan 29 '22 at 06:05
  • 1
    [mcve] please .. – kleopatra Jan 29 '22 at 06:06
  • Please apply the formatting function of your IDE to your code (to correct indentation problems) and remove unnecessary whitespace before posting the code online. – jewelsea Jan 30 '22 at 01:30

0 Answers0