Nick
Nick

Reputation: 6940

Clear SharedPreferences from preference screen item

I have a live wallpaper on the market right now with lots of customizable options. My friend recently asked me to implement a Reset button to bring them all back to their defaults. I added the button to the preferences screen through XML, but I can't get it to clear the preferences. Here's the code I'm using:

getPreferenceManager().findPreference("default").setOnPreferenceClickListener(new OnPreferenceClickListener() {

        public boolean onPreferenceClick(Preference preference) {
            AlertDialog alertDialog = new AlertDialog.Builder(mContext).create();
            alertDialog.setMessage("Are you sure you want to reset all settings to default?");
            alertDialog.setCancelable(true);
            alertDialog.setButton("Yes", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    SharedPreferences settings =  PreferenceManager.getDefaultSharedPreferences(getBaseContext());                          
                    SharedPreferences.Editor editor = settings.edit();
                    editor.clear();
                    editor.commit();
                } }); 
            alertDialog.setButton2("No", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                } }); 
            alertDialog.show();
            return false;
        }
    });

The AlertDialog pops up, clicking on "No" cancels the box, but clicking on "Yes" closes the box without clearing the preferences. What should I change to get them to clear? Thanks guys!

EDIT: A little update, adding a

Log.d("test" , settings.getAll().toString());

Before and after the clear/commit returns {} both times. So I think I stored my preferences in some weird way or something

Upvotes: 0

Views: 1850

Answers (2)

Nick
Nick

Reputation: 6940

Okay, I figured it out. I was saving the preferences with the name myPrefs, so instead of calling PreferenceManager.GetDefaultSharedPreferences I called getPreferenceManager().getSharedPreferences(). Thanks for the help Kenny!

Upvotes: 1

Kenny
Kenny

Reputation: 5542

Have you tried using editor.apply(); rather than commit? This will work fine as long as your calling it on the main thread, and nothing else tries to commit().

apply() commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk so you won't be notified of any failures.

Upvotes: 0

Related Questions