I've got an ArrayList of a custom object that includes an array. I want to save it to file but when I reload it, the array isn't reloaded.
Is there a way to save it?
That's my class:
public class Dates {
public Date date;
public String team;
public String [] players;
public Dates (Date date, String team, String [] players) {
this.date = date;
this.team = team;
this.players = players;
}
}
That's how I create the ArrayList:
public ArrayList<Dates> dates = new ArrayList<>();
How I save and load it:
public static void saveDates(Context context, ArrayList<Dates> callLog) {
SharedPreferences mPrefs = context.getSharedPreferences("Dates", context.MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(callLog);
prefsEditor.putString("myDates", json);
prefsEditor.apply();
}
public static ArrayList<Dates> loadDates(Context context) {
ArrayList<Dates> callLog;
SharedPreferences mPrefs = context.getSharedPreferences("Dates", context.MODE_PRIVATE);
Gson gson = new Gson();
String json = mPrefs.getString("myDates", "");
if (json.isEmpty()) callLog = new ArrayList<>();
else {
Type type = new TypeToken<List<Dates>>() {
}.getType();
callLog = gson.fromJson(json, type);
}
return callLog;
}
My problem:
String [] player = {"Spieler", "Spieler2", "Spieler3"};
dates.add(new Dates(Calendar.getInstance().getTime(), "F5", player));
saveDates(MainActivity.this, dates);
dates = loadDates(MainActivity.this);
Toast.makeText(MainActivity.this, Integer.toString(dates.get(0).players.length), Toast.LENGTH_SHORT).show();
If I use the first three lines, the length of the array is 3. But if I don't use this three lines, I get a NullPointerException in dates.get(0).players.length because I attempt to get length of null array.
Thanks for your help.