I created the PreferencesHelper class proposed by Mridul S Kumar here but, for some reason, the warning was still showing up. To ignore the message with @SuppressLint("CommitPrefEdits")
was my last resort. That's why I dug a little deeper and I tried the approach mentioned in this post and found out that the message was gone.
So I realized that the solution is to call the apply() method inside the method where the editor instance variable is initialized, without using "this" (I don't recommend you use commit() because then Android will advise you, with another warning, to consider using apply() instead, on the grounds that "commit writes its data to persistent storage, whereas apply will handle it in the background").
I'm not sure why, but what I do know is that there is no need to use it in this case, according to this post. The variable editor is not a reference to be disambiguated.
Therefore, the following code should solve your problem:
public class PreferencesHelper {
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
public PreferencesHelper(Context context) {
this.sharedPreferences = context.getSharedPreferences("MyPreference", 0);
this.editor = sharedPreferences.edit();
boolean firstTime = sharedPreferences.getBoolean("first", true);
if (firstTime) {
editor.putBoolean("first", false);
editor.apply();
}
}
public String GetPreferences(String key) {
return sharedPreferences.getString(key, "");
}
public void SavePreferences(String key, String value) {
editor.putString(key, value);
editor.commit();
}
}
}
I'm using Android 3.1.4, by the way.