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?
I think the problem might be in:
only call
saveBudget
inonResume()
onResume()
. Check this Android Activity Lifecycle . SharedPreferences
instance. To get SharedPreferences
use:SharedPreferences sP = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences from different activity
You can try this, I hope this will compile:
public static final String SHARED_PREFS = "NAME_OF_SP";
public static final String NAME_OF_VAL = "budget";
public void saveBudget()
{
SharedPreferences sharedPref = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
Gson gson = new Gson();
String json = gson.toJson(budget);
Log.d("BTAG", "JSON: " + json);
editor.putString(NAME_OF_VAL, json);
editor.apply();
}
public Budget getBudget()
{
SharedPreferences sharedPref = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPref.getString(NAME_OF_VAL, null);
Log.d("BTAG", "gson from json: " + gson.fromJson(json, Budget.class));
return gson.fromJson(json, Budget.class);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.