0

I have declared two share preferences within an activity. The two shared preferences are controlled with a logic if block as shown

      if(logic == true){
       // remove shared preferences of a particular keyname
        SharedPreferences sharedPreferencesGiver = getSharedPreferences("editorCodeGiver", Context.MODE_PRIVATE);
//assuming that editorCodeGiver is the name of the shared preferences declared below in the else block
                            SharedPreferences.Editor editGiv = sharedPreferencesGiver.edit();
                            editGiv.clear().commit();
        }else{
    //dont clear shared preferences

        SharedPreferences sharedPrefCodeGiver = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                                SharedPreferences.Editor editorCodeGiver = sharedPrefCodeGiver.edit();
                                editorCodeGiver.putInt("statusCodeGiver", 202); //
                                editorCodeGiver.commit();

    }

Please how can I clear the shared preferences declared in the else block

parker
  • 255
  • 2
  • 6
  • 21

2 Answers2

1
SharedPreferences sharedPrefCodeGiver = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                                SharedPreferences.Editor editorCodeGiver = sharedPrefCodeGiver.edit();
                                //editorCodeGiver.putInt("statusCodeGiver", 202);  <- change this line
                                editorCodeGiver.remove(String key); // <- to this
                                editorCodeGiver.commit();

Information:

You don't use the same SharedPreference, one time it's

getSharedPreferences("editorCodeGiver", Context.MODE_PRIVATE);

and the other time:

PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

Check this answer to know how to choose the right instance https://stackoverflow.com/a/9513032/4690394

NeoSyder
  • 23
  • 6
  • what does this mean Context.MODE_PRIVATE as opposed to the other getApplicationContext() – parker Jun 16 '17 at 08:36
  • It's not the same thing, Context.MODE_PRIVATE is the mode in which the shared preferences will be created. It's the default mode, where the created file can only be accessed by the calling application (only your app). And if you pay attention to the link I sent you, the second method PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); call automatically context.getSharedPreferences with the private mode. https://stackoverflow.com/a/6310080/4690394 – NeoSyder Jun 16 '17 at 08:51
  • getApplicationContext is a ref to your Application, but you can pass an activity or a service in this case – NeoSyder Jun 16 '17 at 08:56
0

for clear all of sharedPreferences values do this

mSharedPreferences.edit().clear().commit();

this line clear all values

for clear one value you can do this:

 mSharedPreferences.edit().putString("keyName",null).commit();
faraz khonsari
  • 1,924
  • 1
  • 19
  • 27