gpt4 book ai didi

java - 通过共享首选项保存 Activity

转载 作者:行者123 更新时间:2023-12-02 02:46:45 27 4
gpt4 key购买 nike

我在保存 Activity 状态时遇到问题,我使用共享首选项来保存信息。当我单击按钮时,它将其保存到共享首选项中并完成 Activity :

sharedPreferences = this.getSharedPreferences("my_Pref", Context.MODE_PRIVATE);
sharedPreferences.edit().putInt(AGE_SCORE, sbAge.getProgress()).apply();
sharedPreferences.edit().putInt(STATUS_SCORE, spMyStatus.getSelectedItemPosition()).apply();
if (rbFemaleMe.isChecked())
sharedPreferences.edit().putInt(SEX_SCORE, 1).apply();
else if(rbMaleMe.isChecked())
sharedPreferences.edit().putInt(SEX_SCORE, 2).apply();
sharedPreferences.edit().commit();
finish();

关闭 Activity 后,我第二次打开它,但没有任何反应,

我的 onCreate() 方法:

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
if(sharedPreferences!= null)
{
sharedPreferences = getSharedPreferences("my_Pref", MODE_PRIVATE);

sbAge.setProgress(sharedPreferences.getInt(AGE_SCORE, 0));
spMyStatus.setSelection(sharedPreferences.getInt(STATUS_SCORE, 0));
if(sharedPreferences.getInt(SEX_SCORE, 0) == 1)
rbMaleMe.isChecked();
else if (sharedPreferences.getInt(SEX_SCORE, 0) == 2)
rbFemaleMe.isChecked();
}

最佳答案

同时使用 apply()commit() 对我来说似乎多余,尝试进行所有编辑,然后使用 commit()与磁盘写入同步。

Difference in commit() and apply()

    sharedPreferences = this.getSharedPreferences("my_Pref", Context.MODE_PRIVATE);
SharedPreferences.Editor edit = sharedPreferences.edit();
edit.putInt(AGE_SCORE, sbAge.getProgress());
edit.putInt(STATUS_SCORE, spMyStatus.getSelectedItemPosition());
if (rbFemaleMe.isChecked())
edit.putInt(SEX_SCORE, 1);
else if(rbMaleMe.isChecked())
edit.putInt(SEX_SCORE, 2);
edit.commit();
finish();

问题出在您检查sharedpreferences != null,但启动时它始终为null。首先使用 getApplicationContext().getSharedPreferences("my_Pref", MODE_PRIVATE); 初始化它。

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);

sharedPreferences = getApplicationContext.getSharedPreferences("my_Pref", MODE_PRIVATE);

if(sharedPreferences != null)
{

sbAge.setProgress(sharedPreferences.getInt(AGE_SCORE, 0));
spMyStatus.setSelection(sharedPreferences.getInt(STATUS_SCORE, 0));
if(sharedPreferences.getInt(SEX_SCORE, 0) == 1)
rbMaleMe.isChecked();
else if (sharedPreferences.getInt(SEX_SCORE, 0) == 2)
rbFemaleMe.isChecked();
}

关于java - 通过共享首选项保存 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44456219/

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