I'm writing some code that turns airplane mode on or off (depending on user choice) when the screen turns on. I've kept flags for the user's choice (0 for off and 1 for on). For some reason though, no matter what the user picks, the value for the choice (airplanei) is always 1 in the activity. I'm sure the error is somewhere in the code I've posted; incorrect use of SharedPreferences most likely.
Code for Activity:-
protected void airplane(int i) {
// Store flag in SharedPreferences
SharedPreferences flags = this.getSharedPreferences("toggleflags",
MODE_WORLD_READABLE);
SharedPreferences.Editor editor = flags.edit();
if (i == 0)
editor.putInt("airplanei", 0);
else if (i == 1)
flags.edit().putInt("airplanei", 1);
else if (i == -1)
flags.edit().putInt("airplanei", -1);
editor.commit();
}
Code in Broadcast Reciever: -
public class Screen_On extends BroadcastReceiver{
@Override
public void onReceive(final Context context, Intent intent) {
SharedPreferences flag = context.getSharedPreferences("toggleflags", 0);
int i = flag.getInt("airplanei", 1);
if (i == 0) {
//Code to turn airplane mode off
} else if (i == 1) {
//Code to turn airplane mode on
}
}
}
Thanks for your time.
As @Matt already said you actually create two new instances of Editor
but commit only first:
flags.edit().putInt("airplanei", 1); // New editor here
...
flags.edit().putInt("airplanei", -1);
...
editor.commit(); // Commit first editor instance