2

I'm not new to sharedPreferences, and I decided to use them to store the titles of courses in which users create, and then are loaded into a listView. The course titles are stored in a set which is then put into the sharedPreference. The issue here is when i input the first course(as a user), it gets saved persistently, but adding more courses also saves as well, and works while the app is active, but on app restart, the sharedPreference returns back to the initial value of only one item in the set.

Naturally, i looked up the issue, and was able to solve it by using editor.clear() which i got from this reference https://looksok.wordpress.com/2012/09/21/sharedpreferences-not-saved-after-app-restart/

Notice that the solution was described as "the tricky one". I really want to know what this line meant. I've checked on the issue, but still can't understand why this case is so different, and such abnormalities scare me whenever i use those classes. So here's my code:

    // Shared Preferences
    SharedPreferences customPrefs;

    // Editor for Shared preferences
    SharedPreferences.Editor editor;

    private CustomCourseDBHelper customDBHelper;

    private final static int ADD_CUSTOM_COURSE_REQUEST = 1;
    private final static int EDIT_CUSTOM_COURSE_REQUEST = 2;
    private final static String TITLE_PREFS = "customCourseTitles";
    private final static String TITLE_PREF_LIST = "customCourseList";

    private ListView cListView;
    private Set<String> allTitles = new LinkedHashSet<>();

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.custom_course_list);

        mToolbar = (Toolbar) findViewById(R.id.tool_bar_shadow);
        cListView = (ListView) findViewById(R.id.customQuestionList);
        addButton = (FloatingActionButton) findViewById(R.id.addButton);

        cAdapter = new CustomCourseAdapter(this);

        setSupportActionBar(mToolbar);

        cListView.setAdapter(cAdapter);

        //declare shared prefs
        customPrefs = getSharedPreferences(TITLE_PREFS, MODE_PRIVATE);

        //set on long press options
        optionsList.add("Delete Course");

        //set icon for add button
        addButton.setImageDrawable(getResources()
                .getDrawable(R.drawable.ic_add_white_24dp));

        addButton.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v) {
                Intent i = new Intent(CustomCourseList.this, AddCustomCourseActivity.class);
                startActivityForResult(i, ADD_CUSTOM_COURSE_REQUEST);
            }

        });
}

And here's where the saving occurs

        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data){
            if (resultCode == RESULT_OK && requestCode == ADD_CUSTOM_COURSE_REQUEST){
                CustomCourseItem cci = new CustomCourseItem(data);
                cAdapter.add(cci);

                //save the provided details in a database
                customDBHelper = new CustomCourseDBHelper(this, cci.getPath());
                customDBHelper.addCustomCourse(cci);

                editor = customPrefs.edit();

                Set<String> mSet = customPrefs.getStringSet(TITLE_PREF_LIST, null);

                if (mSet != null)
                    allTitles = mSet;

                //store the given database names in a set in a shared preference
                allTitles.add(cci.getPath());
                editor.clear(); //this line here, without it, the sharedPref is not persistent, 
                //i didn't see any clear reason as to why this occurs, when i read the documentary
                editor.putStringSet(TITLE_PREF_LIST, allTitles);
                editor.commit();
            }


            //listen request for edits made to courses
            if (resultCode == RESULT_OK && requestCode == EDIT_CUSTOM_COURSE_REQUEST){
                if (data.getBooleanExtra("edited", false)){
                    restructureDbOnEdit();
                }
            }

        }

PS. i omitted some unnecessary code like UI implementations and other non-sharedPreference related stuff. So even though the app runs well now, any further insight on this issue would be really welcomed.

Mofe Ejegi
  • 733
  • 11
  • 20
  • I tested your way of saving the shared preferences by using only an editText and button to save and added a log to see what's in "allTitles". Even after I close the app and start it again, the previously saved titles are still there. – cherry-wave Jan 25 '16 at 10:09
  • Did you remove the editor.clear(); line ? – Mofe Ejegi Jan 25 '16 at 10:24
  • What is the return value of `editor.commit()`? Please post that value. – Mustansar Saeed Jan 25 '16 at 10:25
  • With or without the clear() command, commit() always returns true. It really is a confusing situation. – Mofe Ejegi Jan 25 '16 at 17:16
  • I believe that when I use the put() method, if the key existed previously, it replaces the previous value, but in this case, it always reverts back to the original after the app restarts. – Mofe Ejegi Jan 25 '16 at 21:36
  • No that can't be. As I said I use exactly your way of saving it and it works! I don't know maybe something is wrong with your ListView? Did you place some log-outputs? – cherry-wave Jan 26 '16 at 08:15

1 Answers1

1

Well I finally found what went wrong after doing a proper search, check out the answer provided here. Note that this is a bug in android and happens to string sets only. Thanks Set<String> in android sharedpreferences does not save on force close

Community
  • 1
  • 1
Mofe Ejegi
  • 733
  • 11
  • 20