I am a beginner and I've complete the project. Now, I successfully serialize the objects in the ArrayList, and when opening the program again, I want the program to load the data.
However, when I deserialize, I use another ArrayList and add the objects first. Then, set it to the original one. It failed. I can no longer use my methods to call them.
I am sure that I serialize the object properly that I can call them using the getters in the NimPlayer
when deserializing.
How I serialize and deserialize:
private void saveData() {
ArrayList<NimPlayer> playerList = nimModel.getPlayerList();
if (playerList.size() != 0) {
try {
FileOutputStream fileOut =
new FileOutputStream("players.dat.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(playerList);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in players.dat.ser");
} catch (IOException i) {
i.printStackTrace();
}
} else {
System.out.println("There is no data to be stored.");
}
}
private void loadData(String fileName) {
NimModel nimModel = new NimModel();
try {
FileInputStream fis = new FileInputStream(fileName);
ObjectInputStream ois = new ObjectInputStream(fis);
ArrayList<NimPlayer> newPlayerList = (ArrayList<NimPlayer>)ois.readObject();
nimModel.setPlayerList(playerList);// I THOUGHT IT WOULD WORK
} catch (IOException i) {
i.printStackTrace();
return;
}
}
Here is part of my NimPlayer
class
public class NimPlayer implements Serializable {
private final String userName;
private String familyName;
private String givenName;
private int gamesPlayed;
private int gamesWon;
public NimPlayer(String userName, String familyName, String givenName) {
this.userName = userName;
this.familyName = familyName;
this.givenName = givenName;
this.gamesPlayed = 0;
this.gamesWon = 0;
}
//getter and setters
}
And the getters and setters of ArrayList is in the NimModel
:
public class NimModel {
private ArrayList<NimPlayer> playerList = new ArrayList<NimPlayer>();
public ArrayList<NimPlayer> getPlayerList() {
return new ArrayList<NimPlayer>(playerList);
}
public void setPlayerList(ArrayList<NimPlayer> playerList) {
this.playerList = playerList;
}
public void displayAllPlayers() {
Collections.sort(playerList, (NimPlayer p1, NimPlayer p2) -> {
return p1.getUserName().compareToIgnoreCase(p2.getUserName());
});
if (playerList.size() != 0) {
for (NimPlayer player : playerList) {
String userName = player.getUserName();
String familyName = player.getFamilyName();
String givenName= player.getGivenName();
int gamesWon = player.getGamesWon();
int gamesPlayed = player.getGamesPlayed();
System.out.println(userName + "," + familyName + "," + givenName + "," + gamesPlayed + " games," + gamesWon + " wins");
}
} else {
System.out.println("There is no players.");
}
}
}
Any help is highly appreciated
reference
Getters and Setters for ArrayLists in Java