本文介绍了当我切换活动或关闭应用程序时,Android 中的共享首选项不会保存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我检查了类似的问题,注意到似乎有效.我无法弄清楚似乎是什么问题.每次应用重启或活动切换后,值都会变为 0.
I checked similar questionsions and noting seems to work. I can't figure out what seems to be the problem. Value goes to 0 after every app restart or activity switch.
//just parts of code from activity1
SharedPreferences pref;
SharedPreferences.Editor editor;
// On create....
pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
editor = pref.edit();
max=pref.getInt("mxtime", 0);
//If something>something...
editor.putInt("mxtime", max);
editor.commit();
在第一部分中,我在主活动中声明了 SharedPreferences.我将它保存在max"int 中,并且它在启动时始终为 0,因为如果空值为 0.在第二个活动中,我有一个按钮,点击它应该清空 SharedPreferences 中的值.
In the first part i declare SharedPreferences in main Activity. I save it in "max" int and its always 0 on startup since if empty value is 0. On second activity I have a button, where on click it should empty the value from SharedPreferences.
活动 2:
public class settings extends AppCompatActivity {
private Button myButton;
private Button myButton2;
private Button myButton3;
//sharedPrefs
SharedPreferences pref;
SharedPreferences.Editor editor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
editor = pref.edit();
myButton = (Button) findViewById(R.id.button3);
myButton2 = (Button) findViewById(R.id.button4);
myButton3 = (Button) findViewById(R.id.button5);
myButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(),MainActivity.class);
startActivity(i);
}
});
myButton2.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
//sharedPrefs
editor.remove("mxtime");
editor.commit();
}
});
}
}
推荐答案
尝试像这样使用 SharedPreferences:
Try to use SharedPreferences like this:
SharedPreferences preferences = getApplicationContext().getSharedPreferences("loginPref", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
这篇关于当我切换活动或关闭应用程序时,Android 中的共享首选项不会保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!