I'm developping my app using the MVC pattern. To store/access data, my controllers use a class named "DataStorage", and for now this class allows to store/access simple parameters about my app (username, data storage path, ...). In other words, I want to call a few methods like "getParameter(String key)" or "setParameter(String key, String value)". I think SharedPreferences would be the most convenient way to store these parameters, so my get/setParameters use this class.

In all the examples I have seen, SharedPreferences is called from an Activity and there is no problem to call methods such as "getSharedPreferences" or "getApplicationContext"/"getContext". Because my DataStorage class is not an activity, for now I ask my first activity to give its context when creating a new DataStorage instance, and it works well to store my parameters. My problem : I want to be able to remove parameters from another activity using clear + commit methods. But it doesn't work (parameters are still there), and I think the reason is I give the 2nd activity context when creating another instance of DataStorage. The problem might be something else though, I've been practicing Android for only 2 days now...

To summarize how my app works :

  • Activity 1 creates a DataStorage class and provides its context to the DataStorage constructor. The DataStorage might store a parameter into a SharedPreferences file (or not...)

  • When I run my app again, if a particular parameter is set in the SharedPreferences file, then I start Activity 2 instead of Activity 1. Using the menu on Activity 2, I want to be able to clear the SharedPreferences file (in order to get Activity 1 again when I restart the app), so I create another DataStorage instance (and I provide Activity 2 context) and I call the method to clear all parameters.

As I said, first part works well (I can store parameters), but clear & commit do nothing to my SharedPreferences file. I don't want to put a piece of code for this directly in my activities.

The DataStorage method I use to clear my file :

public void clearPreferences() {
        settings.edit().clear();
        settings.edit().commit();
        Toast.makeText(context,"Preferences removed", Toast.LENGTH_LONG).show();
    }

More information :

  • The SharedPreferences filename is set when constructing the DataStorage instance, and it's the same in both Activity 1 & 2.

  • I use Context.MODE_PRIVATE when getting the SharedPreferences file

Can you help me with this ? What am I doing wrong in the way I use SharedPreferences ?

Thank you for your help !

Related posts

Recent Viewed