我想清除我在第一个活动中放置的所有 sharedpref 并在第二个活动中删除它。但是清除功能不起作用..这是我的代码
public class MyActivity extends Activity implements View.OnClickListener {
/**
* Called when the activity is first created.
*/
public static final String PREFS_NAME = "ResumePrefs";
SharedPreferences settings;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
((Button)findViewById(R.id.button)).setOnClickListener(this);
}
@Override
protected void onResume() {
try{
Toast. makeText(this,settings.getString("answer_id",""),Toast.LENGTH_LONG).show();
}catch (Exception e){
Toast.makeText(this,e.toString(),Toast.LENGTH_LONG).show();
}
super.onResume();
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.button:
settings = getSharedPreferences(PREFS_NAME, 1);
SharedPreferences.Editor editor = settings.edit();
editor.putString("answer_id", "This is a test");
editor.commit();
Intent intent = new Intent(this,destroyPref.class);
startActivity(intent);
break;
}
}
}
和我的第二个活动:
public class destroyPref extends Activity {
public static final String PREFS_NAME = "ResumePrefs";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.destroy);
}
@Override
public void onBackPressed() {
SharedPreferences settings = this.getSharedPreferences(PREFS_NAME,1);
settings.edit().clear();
settings.edit().commit();
super.onBackPressed();
}
@Override
protected void onResume() {
SharedPreferences settings = this.getSharedPreferences(PREFS_NAME,1);
settings.edit().clear();
settings.edit().commit();
super.onResume();
}
}
一旦我按下后退按钮,我将返回主要活动并期望清除偏好值,除非我再次按下按钮。我尝试了 bot backpress 和 resume,但 sharedpref 值仍然存在。我错过了什么吗?谢谢。