0

I have a boolean variable public static boolean isInDarkTheme but when I try to change the value in my settings activity it only gets changed tempolarily. I did it so:

                if (on) {
                //Do something when Switch button is on/checked
                MainActivity.isInDarkTheme = true;
            } else {
                //Do something when Switch is off/unchecked
                MainActivity.isInDarkTheme = false;
            }
            Log.d("DarkTheme", "SETTINGS " + MainActivity.isInDarkTheme);

in my settings the variable is changed but when I go back to my main with the arrow I created with this:

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

picture with this button

it is still the same in the main

but! when I use my software key to get back to the MainActivity it get saved picture with software back key

Any idea what I can do that it get saved with the other button?

MrMinemeet
  • 304
  • 6
  • 17

2 Answers2

0

your variable will not be saved and will be collected by garbage collector once the activity is destroyed.

you have to use something like SharedPreferences.

to save the variable

SharedPreferences sharedPrefrences = getSharedPreferences("pref_name", MODE_PRIVATE);
        sharedPrefrences.edit().putBoolean("isDarkTheme", true).apply();

to load

SharedPreferences sharedPrefrences = getSharedPreferences("pref_name", MODE_PRIVATE);
                                           //   key   ,   default value
        boolean isDark= sharedPrefrences.getBoolean("isDarkThem", false);

read about SharedPreferences here

MSpeed
  • 8,153
  • 7
  • 49
  • 61
Bishoy Kamel
  • 2,327
  • 2
  • 17
  • 29
0

The most likely reason is that both activities are loaded by different class loaders with the effect that the MainActivity you "see" in your Settings activity is a different one than the one you "see" in your other activity. You can find that out by logging the classloader "attached" to the MainActivity by calling MainActivity.class.getClassLoader()

Lothar
  • 5,323
  • 1
  • 11
  • 27