Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SharedPreferences - Android

I have a little doubt about the SharedPreferences in Android.

To delete a preference, we mainly have two options:

First:

SharedPreferences.Editor edit = (Editor) getSharedPreferences(Constants.APP_DEFAULT_PREF, MODE_PRIVATE).edit();
edit.putString(Constants.PREF_ACC, null);
edit.commit();

Second:

SharedPreferences.Editor edit = (Editor) getSharedPreferences(Constants.APP_DEFAULT_PREF, MODE_PRIVATE).edit();
edit.remove(Constants.PREF_ACC);
edit.commit();

In either case, fetching Constants.PREF_ACC value from SharedPreferences will return null.

I was wondering which one should I prefer. Is there any memory related issues in either of them? What will the System.gc behavior be with them?

like image 665
cprakashagr Avatar asked Apr 10 '26 17:04

cprakashagr


1 Answers

Theoretically remove is better than put(null), because it removes both the key and value (once committed) instead of mapping (and keeping) the key to a null value.

But judging by the Android 5.1.1 implementation, they are equivalent :

    ...
    String k = e.getKey();
    Object v = e.getValue();
    // "this" is the magic value for a removal mutation. In addition,
    // setting a value to "null" for a given key is specified to be
    // equivalent to calling remove on that key.
    if (v == this || v == null) {
        if (!mMap.containsKey(k)) {
            continue;
        }
        mMap.remove(k);
    } else {
    ...

That is also what one of the putXXX methods (putStringSet) documentation says :

Passing null for this argument is equivalent to calling remove(String) with this key.

like image 60
bwt Avatar answered Apr 12 '26 07:04

bwt