I am making a simple budget tracking app. I have a Budget class that stores a few variables: the amount, duration, and initial value of budget. I only have one global Budget object inside the fragment, called "budget", and am trying to get it to save. It seems to save fine, but when I try to retrieve it, it returns the default value for some reason. Here are my methods for saving and loading. I only call getBudget() in onCreateView, and only call saveBudget in onResume() and after the budget is edited. Note the log entries.
public void saveBudget(){
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.clear();
Gson gson = new Gson();
String json = gson.toJson(budget);
Log.d("BTAG", "JSON: " + json);
editor.putString("current budget", json);
editor.commit();
}
public Budget getBudget(){
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPref.getString("current budget", null);
Log.d("BTAG", "gson from json: " + gson.fromJson(json, Budget.class));
return gson.fromJson(json, Budget.class);
}
My log says this for my current instance of Budget:
D/BTAG: JSON: {"amount":35.92,"frequency":"monthly","originalAmount":35.92}
D/BTAG: gson from json: null
This shows that it saves without issue, but loading doesn't work. Why is getBudget() not working?