Why aren't my SharedPreferences loading right after application launch?
I’m using SharedPreferences
to store user input so that when application is closed and then re-launched the user input stays there and not auto deletes itself. But, when I re-launch the application after closing it the user input doesn’t appear on screen until the user adds another input. After the user adds another input, the inputs that were added in the session before closing the application now appear on screen. Any idea why this might be happening? Thanks!
This is what’s happening in case a visual example is needed.
This is the method that’s in charge of loading what the user inputed and I call this method on the onCreate
method:
public void loadSemesters() { sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE); Gson gson = new Gson(); String json = sharedPreferences.getString("SEMESTER_LIST", null); Type type = new TypeToken<ArrayList<Semester>>() { }.getType(); mySemesters = gson.fromJson(json, type); if (mySemesters == null) { mySemesters = new ArrayList<>(); } }
This method is in charge of saving the user input:
public void saveSemesters() { sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); Gson gson = new Gson(); Type type = new TypeToken<ArrayList<Semester>>() { }.getType(); String json = gson.toJson(mySemesters, type); editor.putString("SEMESTER_LIST", json); editor.apply(); }
As a solution i guess you forgot to set the data to your views ( Update UI ) after the app restarts so you need to update your UI
public void loadSemesters() { sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE); Gson gson = new Gson(); String json = sharedPreferences.getString("SEMESTER_LIST", null); Type type = new TypeToken<ArrayList<Semester>>() { }.getType(); mySemesters = gson.fromJson(json, type); //Your have your semeters arraylist , now get the data from the list and //set it to // your views if (mySemesters == null) { mySemesters = new ArrayList<>(); } }