如何删除共享偏好

时间:2015-08-13 06:05:22

标签: android sharedpreferences

我想删除在注册活动中注册用户时创建的共享首选项 用于在RegisterActivity文件中保存共享首选项的代码是:

spf = getSharedPreferences(MyPref,0);
    SharedPreferences.Editor editor=spf.edit();
    editor.putString(name, txtfullname.getText().toString()); //name is a key which will help to identify.. abhi tera name is null.. its jus a variable now no key identifying value in it..
    editor.putString(age, txtage.getText().toString());//same for other two i.e age and ph_no these must b string keys
    editor.putString(ph_no, txtmobileno.getText().toString());
    editor.putString(email, txtemailid.getText().toString());
    editor.putString(password, txtpasskey.getText().toString());
    if(radio1.isChecked())
    {
        flag="Male";
    }
    else
    {
        flag="Female";
    }
    editor.putString(gender,flag);
    editor.putString(spinner_text, spinnertext);
    editor.commit();

现在我要删除上面保存的此偏好设置 我在另一项活动中使用此代码:

SharedPreferences pref = getPreferences(0);
        SharedPreferences.Editor editoer = pref.edit();
        editoer.clear();
        editoer.commit();
        finish();

但是我无法以这种方式删除它,任何建议我应该怎么做?

4 个答案:

答案 0 :(得分:1)

Use this code

SharedPreferences myPrefs =      
v.getContext().getSharedPreferences(MyPref,Context.MODE_PRIVATE)
SharedPreferences.Editor editor = myPrefs.edit();
editor.clear();
editor.commit();  

答案 1 :(得分:1)

将SP替换为“”

SharedPreferences.Editor editor=spf.edit();
    editor.putString(name, ""); //name is a key which will help to identify.. abhi tera name is null.. its jus a variable now no key identifying value in it..
    editor.putString(age, "");//same for other two i.e age and ph_no these must b string keys
    editor.putString(ph_no, "");
    editor.putString(email, "");
    editor.putString(password, "");
    editor.putString(gender,"");
    editor.putString(spinner_text,"");
    editor.commit();

答案 2 :(得分:1)

您的偏好设置错误,您的偏好设置名称为" MyPref"比你必须得到的偏好名称和清除偏好,例如:

SharedPreferences pref = getPreferences(MyPref,0);
Editor editoer = pref.edit();
editoer.clear();
editoer.commit();

答案 3 :(得分:0)

拥有SharedPreference.Editor对象后,您可以通过调用remove()方法并使用键作为参数轻松删除键对值。

editor.remove(String key);
editor.apply();