问题
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();
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.
Activity 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();
}
});
}
}
回答1:
Try to use SharedPreferences like this:
SharedPreferences preferences = getApplicationContext().getSharedPreferences("loginPref", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
回答2:
Activity 1:
SharedPreferences sp = getSharedPreferences("YourSharedPreference", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
int DEFAULT_VALUE = 0;
editor.putInt("VARIABLE_KEY", DEFAULT_VALUE);
//If something > something..
int VALUE_TO_PASS = <your value here>;
editor.putInt("VARIABLE_KEY", VALUE_TO_PASS);
// Before screen shift
editor.commit();
...........................................
Activity 2:
SharedPreferences sp = getSharedPreferences("YourSharedPreference", Activity.MODE_PRIVATE);
int DEFAULT_FALLBACK_VALUE = 0; //When value is not received, show this
int VALUE_PASSED = sp.getInt("VARIABLE_KEY", DEFAULT_FALLBACK_VALUE);
// On button click:
int DEFAULT_VALUE = 0;
editor.putInt("VARIABLE_KEY", DEFAULT_VALUE);
editor.commit();
来源:https://stackoverflow.com/questions/36541997/shared-preferences-in-android-doesnt-save-when-i-switch-activity-or-close-app