gpt4 book ai didi

android 不清除 sharedpreference

转载 作者:太空宇宙 更新时间:2023-11-03 11:44:31 30 4
gpt4 key购买 nike

我想清除我在第一个 Activity 中放置的所有 sharedpref,并在第二个 Activity 中将其删除。但是清除功能不起作用..这是我的代码

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;
}
}
}

和我的第二个 Activity :

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

一旦我按下后退按钮,我将返回到主要 Activity 并期望清除首选项值,除非我再次按下该按钮。我尝试了 bot backpress 和 resume 但 sharedpref 值仍然存在..我错过了什么吗?谢谢。

最佳答案

试试这个:

SharedPreferences.Editor editor = settings.edit();
editor.clear();
editor.commit();

谢谢。

关于android 不清除 sharedpreference,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14481453/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com