I am trying to get a saved value from an activity by this Settings.getMode();
Here is the Settings
class :
public class Set extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
private static String isNightMode;
Switch aSwitch;
Boolean mode;
@Override
protected void onCreate(Bundle savedInstanceState) {
SharedPreferences sharedPreferences = getSharedPreferences("xyz", MODE_PRIVATE);
isNightMode = sharedPreferences.getString("isNightMode", "no");
mode = sharedPreferences.getBoolean("mode", false);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_set);
aSwitch = (Switch) findViewById(R.id.switch1);
aSwitch.setChecked(mode);
if (aSwitch.isChecked()) {
isNightMode = "yes";
} else {
isNightMode = "no";
}
aSwitch.setOnCheckedChangeListener(this);
}
public static String getMode() {
return isNightMode;
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
isNightMode = "yes";
mode = true;
SharedPreferences.Editor editor = getSharedPreferences("xyz", MODE_PRIVATE).edit();
editor.putString("isNightMode", isNightMode);
editor.putBoolean("mode", mode);
editor.commit();
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
} else {
isNightMode = "no";
mode = false;
SharedPreferences.Editor editor = getSharedPreferences("xyz", MODE_PRIVATE).edit();
editor.putString("isNightMode", isNightMode);
editor.putBoolean("mode", mode);
editor.commit();
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
}
}
When I change the value in Settings
activity , the value is saved perfectly. But problem is , I am not getting the saved value when the app starts . When the app starts, the getMode()
method returns null. There must be something wrong while getting saved value at the time of starting the app. I can't figure out the wrong.