android - 尝试使用keyname清除共享首选项

时间:2017-06-16 08:01:06

标签: java android

我已在活动中声明了两个分享偏好。两个共享首选项由逻辑if控制,如图所示

      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();

    }

请问如何清除else块中声明的共享首选项

2 个答案:

答案 0 :(得分: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();

<强>信息:

一次只使用相同的SharedPreference

getSharedPreferences("editorCodeGiver", Context.MODE_PRIVATE);

而另一次:

PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

检查此答案,了解如何选择正确的实例https://stackoverflow.com/a/9513032/4690394

答案 1 :(得分:0)

清除所有sharedPreferences值,执行此操作

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

此行清除所有值

要清除一个值,您可以执行此操作:

 mSharedPreferences.edit().putString("keyName",null).commit();