【发布时间】:2016-04-11 07:07:12
【问题描述】:
我检查了类似的问题,并指出似乎有效。我无法弄清楚似乎是什么问题。每次应用重启或活动切换后,值都会变为 0。
//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();
在第一部分中,我在主 Activity 中声明 SharedPreferences。我将它保存在“max” int 中,并且它在启动时始终为 0,因为如果空值为 0。在第二个活动中,我有一个按钮,点击它应该清空 SharedPreferences 中的值。
活动二:
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();
}
});
}
}
【问题讨论】:
-
为什么你从你的偏好
editor.remove("mxtime");中删除偏好?并且在哪里您为max设置了一个值? -
我在将其保存到 SharedPrefs 之前设置了最大值。我将 editor.remove 更改为 editor.clear()。
-
为什么你从你的偏好
editor.clear();中删除所有的偏好? which 是您分配给max的值? -
因为该按钮用于重置首选项中的所有值。但即使我不去第二个活动并点击它也不会保存价值。
-
感谢您的帮助,现在找到问题所在了。
标签: java android android-sharedpreferences