以下是提交和回滚 SharedPreferences 以及一般使用它的预期/合理方式吗?
public class Settings {
private static final String PREFS_NAME = "Settings";
private static SharedPreferences preferences = null;
private static SharedPreferences.Editor editor = null;
public static void init(Context context) {
// Activity or Service what ever starts first provides the Context
if (preferences == null)
// getSharedPreference because getPreferences is a method of Activity only (not Service or Context)
preferences = context.getSharedPreferences(PREFS_NAME, 0);
editor = preferences.edit();
}
public static String getEmail() {
return preferences.getString("email", null);
}
public static void setEmail(String email) {
editor.putString("email", email);
}
public static String getPassword() {
return preferences.getString("password", null);
}
public static void setPassword(String password) {
editor.putString("password", password);
}
public static void save() {
editor.commit();
}
public static void rollback() {
editor = preferences.edit();
}
}
这是由 stackoverflow 编辑器强制执行的更多细节。我真的不知道还有什么好说的。
非常感谢专家的反馈。如果可能剪断是合理的,那么它可能会比我在这里找到的所有其他线程更好地解释。