work - shared preference login example in android




Clearing preferences in SharedPreferences in Android, not just Values (6)

from what I can incur out of the SharedPreferences documentation, I can update a preference, add one or clear all preference values in a shared preference file.

But I want to completely clear everything inside a shared preference file, not just the values, but the preferences they refer to as well.


Asfar as i know the only possibility is to use OnDestroy() but your program should be running when the device is shutdown.


If you have a SharedPreferences.Editor object and you call clear(), does this not get you what you want? It will remove all preferences and if you call sharedPref.getAll() it should give you a map of size 0 [I just tested this].

To remove one specific preference, call editor.remove(pref), where pref is the preference name.

PS: Don't forget to commit your changes by calling commit() or apply() method on the editor. apply() is faster as it is asynchronous. commit() is synchronous but returns a boolean indicating if the commit succeeded.


To remove specific values: SharedPreferences.Editor.remove() followed by a commit()

To remove them all SharedPreferences.Editor.clear() followed by a commit()

You use remove() to remove specific preferences, you use clear() to remove them all.

Checkout official documentation on SharedPreferences.Editor.


You will find it in the android.jar file in your sdk folder.

For example mine is in C:\Program Files (x86)\Android\android-sdk\platforms\android-8\android.jar (for SDK version 8, to get a different version the change the "android-8" part of the path)

You can extract the .jar using winzip/7z etc as it is just a zip file in disguise. You will then find the drawables folder in the folders you unzipped.


Android Shared Preference Still visible after Deleting File

I think this code must work

 public static void clearAllPreference(Context context){
        SharedPreferences prefs = context.getSharedPreferences(PREF_FILE, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.clear();
        editor.commit();
    }

Problem with back button in my app

How can you clear SharedPreference when the device is switched off.

You can clear it when the device starts thru BraodcastReceiver.

public class PhoneStateReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(final Context context, Intent intent) {

        if(intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){
            //Clear your `SharedPreference` here.
        }
    }
}

In your manifest add this:

<receiver android:name=".receiver.PhoneStateReceiver">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</receiver>  

Add permission:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />