Solution 1 :
I fixed it by calling saveLedger() in onPause(). Not sure why it works though.
Problem :
I’m making a simple budget app, and I have a POJO in my app called budgetLedger, which looks like this:
import java.io.Serializable;
public class budgetDateAndTime implements Serializable {
int hour, minute, year, month, day;
double amount;
public budgetDateAndTime(int hour, int minute, int year, int month, int day, double amount) {
this.year = year;
this.month = month;
this.day = day;
this.hour = hour;
this.minute = minute;
this.amount = amount;
}
.....
along with some getters and setters. I made an ArrayList of these and am trying to get them to save in SharedPreferences. The problem is that it saves on my phone (Samsung Galaxy Note 9), but does not seem to save on other phones, and it also doesn’t save in the AndroidStudio emulators. Here are my methods for saving and loading the ArrayList:
public static final String LEDGER_PREFS = "LEDGER_PREF";
public static final String NAME_OF_LED = "ledger";
public void saveLedger() {
SharedPreferences sharedPref = getActivity().getSharedPreferences(LEDGER_PREFS, getContext().MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
Gson gson = new Gson();
String json = gson.toJson(budgetLedgerList);
editor.putString(NAME_OF_LED, json);
editor.apply();
}
public ArrayList<budgetDateAndTime> getLedger() {
SharedPreferences sharedPref = getActivity().getSharedPreferences(LEDGER_PREFS, getContext().MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPref.getString(NAME_OF_LED, null);
Log.d("BTAG", "json in getledger: " + json);
Type type = new TypeToken<ArrayList<budgetDateAndTime>>() {}.getType();
ArrayList<budgetDateAndTime> theList = gson.fromJson(json, type);
return theList;
}
I only call saveLedger() in onDestroy(), and I only assign getLedger() to an ArrayList variable in onCreate(). Again, it works on my phone, but not on any other phones that I have tried. Does anybody know why this is happening? The log shows that the json is empty when the app is closed or phone is restarted, so it’s not a display issue. Any help will be appreciated!
Comments
Comment posted by naming conventions in Java
OffTopic: Please follow proper