Basically, I'm making a yahtzee game in MVC. It works fine, but When I try to save a session of a game, It doesn't save the game object containing and arraylist of players. This without stopping the execution which would certainly clear the arraylist of games. Basically, an instance of game has the following fields:
public String name;
public int numberOfPlayers;
public ArrayList<Player> players = new ArrayList<>();
int playerListIndex;
ArrayList<Boolean> checkable;
StandardRules yahtzeeRule = new StandardRules();
public int rounds;
public String date;
The Arraylist of players contains instances of the object Player which has it's own fields and gettters/setters.
I've managed to track the problem to not saving when I call the method:
public void saveGame(Game thisGame) {
DB.saveGame(thisGame);
}
Which in turn calls the class:
public class DB {
private static ArrayList<Game> savedGames = new ArrayList<>();
/**
* Saves the passed member into the database.
* @param game, the member to be saved.
*/
public static void saveGame(Game game) {
for (Game g : savedGames) {
if (g.name.equals(game.name)) {
savedGames.remove(g);
savedGames.add(game);
}
else {
savedGames.add(game);
}
}
}
The saveGame method basically checks the Arraylist of saved games if the name already exists, and if it does it removes the old one and adds the new one. If there is no game by that name, It just adds the game to the list. (I might Implement a MYSQL DB later, but for the sake of making sure the program works first, I'd like to use the arraylist to test things)
I'm under the impression that I need to have a static reference to the DB to ensure that I'm trying to access the same DB all the time and not mix up instances of a DB.
What am I doing wrong here?