Carrm
Carrm

Reputation: 1593

Android : SharedPreferences and MVC pattern

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 :

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.

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

Thank you for your help !

Edit :

public class DataStorage {

    private Context context;
    private String settingsFilename;
    private SharedPreferences settings;

    public DataStorage(Context activityContext, String filename) {
        context = activityContext;
        settingsFilename = filename;
        settings = context.getSharedPreferences(settingsFilename, Context.MODE_PRIVATE);
    }

    public void newSharedPreference(String key, String value) {
        settings.edit().putString(key, value).apply();
        settings.edit().commit();
    }

    public String getSharedPreference(String key) {
        return settings.getString(key, null);
    }

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

In my first activity (the code is part of onCreate method) :

DataStorage storage = new DataStorage(this, getResources().getString(R.string.sharedPreferencesFile));
        username = storage.getSharedPreference("username");
        Toast.makeText(this, username, Toast.LENGTH_LONG).show();
        if (username != null) {
            Intent nextActivity = new Intent(this, ActivityMainMenu.class);
            startActivity(nextActivity);
        } else {
            setContentView(R.layout.activity_name);
        }

In my 2nd activity :

public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        switch(id) {
            case R.id.action_clearSharedPref :
                storage.clearPreferences();
                break;
            case R.id.action_leave :
                System.exit(RESULT_OK);
        }

        return super.onOptionsItemSelected(item);
    }

(Storage is constructed exactly as I did in my first Activity)

I tried to replace "this" by getApplicationContext() in DataStorage constructor, but it didn't work.

Upvotes: 1

Views: 1136

Answers (1)

gio
gio

Reputation: 5020

From Editor Class Overview

Interface used for modifying values in a SharedPreferences object. All changes you make in an editor are batched, and not copied back to the original SharedPreferences until you call commit() or apply().

You need to update to change methods at your DataStorage

public void newSharedPreference(String key, String value) {
        settings.edit().putString(key, value).apply();
}

and

public void clearPreferences() {
    settings.edit().clear().apply();
    Toast.makeText(context,settings.toString(), Toast.LENGTH_LONG).show();
}

Reason of issue is next

    settings.edit().clear(); // clear is ok, but it won't be saved because 
    settings.edit().commit(); // create new editor and commit nothing

Upvotes: 0

Related Questions