我检查了类似的问题,注意似乎有效。我无法弄清楚似乎是什么问题。每次应用重启或活动切换后,值都会变为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中清空值。
活动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();
}
});
}
}