android,java,sharedpreferences,datad在运行期间。我想要的是,如果我关闭或暂停我的应用程序,保存了整数值,所以当我再次打开它时,我可以返回最后一个值。
到目前为止,我已经尝试了1 int来学习如何。
protected void onPause(){
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("valueSave",valueToSave );
editor.commit();
}
@Override
protected void onResume(){
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
}
但是没有保存价值......我做错了什么?
编辑:onCreate添加
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.program);
//SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
//settings = getSharedPreferences(PREFS_NAME, 0);
valueToSave = settings.getInt("valueSave",valueToSave);
答案 0 :(得分:2)
尝试以这种方式使用应用程序上下文获取SharedPreference:
保存首选项:
int valueToSave = 1;
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit();
editor.putInt("someValue", valueToSave);
editor.commit();
从偏好中退出:
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
int savedvalue = settings.getInt("someValue");