问题
I'm using SharedPreferences for my apps' Intro Slider. However, I'm getting an error on this line:
class PrefManager {
private SharedPreferences pref;
private SharedPreferences.Editor editor;
private static final String PREF_NAME = "welcome";
private static final String IS_FIRST_TIME_LAUNCH = "IsFirstTimeLaunch";
PrefManager(Context context) {
int PRIVATE_MODE = 0;
pref = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
void setFirstTimeLaunch(boolean isFirstTime) {
editor.putBoolean(IS_FIRST_TIME_LAUNCH, isFirstTime);
editor.commit();
}
boolean isFirstTimeLaunch() {
return pref.getBoolean(IS_FIRST_TIME_LAUNCH, true);
}
}
editor = pref.edit();
What happens if I don't call commit() or apply() after calling edit()?
回答1:
If you do not call commit() or apply(), your changes will not be saved.
- Commit() writes the changes synchronously and directly to the file
- Apply() writes the changes to the in-memory SharedPreferences immediately but begins an asynchronous commit to disk
回答2:
What happens if I don't call commit() or apply() after calling edit()?
Nothing.
回答3:
Simple Method
sharedPreferences = getSharedPreferences("ShaPreferences", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
boolean firstTime = sharedPreferences.getBoolean("first", true);
if (firstTime) {
editor.putBoolean("first", false);
//For commit the changes, Use either editor.commit(); or editor.apply();.
editor.commit();
Intent i = new Intent(SplashActivity.this, StartUpActivity.class);
startActivity(i);
finish();
} else {
Intent i = new Intent(SplashActivity.this, HomeActivity.class);
startActivity(i);
finish();
}
}
回答4:
You can add @SuppressLint("CommitPrefEdits")
to ignore this message. In my case I am using it, because I want to use the same editor
field in my class.
public class ProfileManager {
private SharedPreferences preferences;
private SharedPreferences.Editor editor;
@SuppressLint("CommitPrefEdits")
@Inject
ProfileManager(SharedPreferences preferences) {
this.preferences = preferences;
this.editor = preferences.edit();
}
public void setAccountID(int accountID) {
editor.putInt(AppConstants.ACCOUNT_ID_KEY, accountID)
.apply();
}
public int getAccountID() {
return preferences.getInt(AppConstants.ACCOUNT_ID_KEY, AppConstants.INVALID_ACCOUNT_ID);
}
}
来源:https://stackoverflow.com/questions/42092753/sharedpreferences-edit-without-a-corresponding-commit-or-apply-call