skip to Main Content

I started to encounter this error when I upgraded the version of the project to androidx. I also upgraded the all implementation sdks. I upgraded min sdk from 16 to 19. Before making these upgrades, dark mode was working fine. After upgrading, if you start the application with dark mode selected, the application opens 2 times. How can I solve this problem?

MainActiviy ;

SwitchCompat nightmodeswitch ;

 if (InıtAplıcation.getInstance().isNightModeEnabled()) {
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
        } else {
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);

        }

  @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);

        nightmodeswitch = (SwitchCompat) findViewById(R.id.nightmodeswitch);


        try {
            if (AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES)
                  nightmodeswitch.setChecked(true);


            nightmodeswitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked) {
                             InıtAplıcation.getInstance().setIsNightModeEnabled(true);
                            
                           Intent intent = getIntent();
                             intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                           finish();
                           startActivity(intent);

                   

                    } else {
                            InıtAplıcation.getInstance().setIsNightModeEnabled(false);
                            
                            Intent intent = getIntent();
                            intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                            finish();
                            startActivity(intent);

                       
                        
                    }


                }
            });
        }catch (Exception e){

        }



        return true;
    }

InıtAplıcation ;

public class InıtAplıcation extends Application {

    public static final String NIGHT_MODE = "NIGHT_MODE";
    private boolean isNightModeEnabled = false;

    private static InıtAplıcation singleton = null;

    public static InıtAplıcation getInstance() {

        if(singleton == null)
        {
            singleton = new InıtAplıcation();
        }
        return singleton;
    }


    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    @Override
    public void onCreate() {
        super.onCreate();

        FirebaseDatabase.getInstance().setPersistenceEnabled(true);

        singleton = this ;
        SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
        this.isNightModeEnabled = mPrefs.getBoolean(NIGHT_MODE, false);
    }

    public boolean isNightModeEnabled() {
        return isNightModeEnabled;
    }

    public void setIsNightModeEnabled(boolean isNightModeEnabled) {
        this.isNightModeEnabled = isNightModeEnabled;

        SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences.Editor editor = mPrefs.edit();
        editor.putBoolean(NIGHT_MODE, isNightModeEnabled);
        editor.apply();
    }
}

ValuesStyles :

<style name="AppTheme.beyaztema" parent="Theme.AppCompat.Light.NoActionBar" >
        <item name="windowActionBar">false</item>
        <item name="colorPrimary">@color/colorappaydınlık</item>
        <item name="colorPrimaryDark">#FFF</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

NightStyles :

  <style name="AppTheme.beyaztema" parent="Theme.AppCompat.Light.NoActionBar" >
        <item name="windowActionBar">false</item>
        <item name="colorPrimary">#000</item>
        <item name="colorPrimaryDark">#000</item>
        <item name="colorAccent">#D81B60</item>
    </style>

Android manifest :

 <application
        android:name=".InıtAplıcation"
        android:allowBackup="true"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme.beyaztema">

gradle:

apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
apply plugin: 'com.google.firebase.crashlytics'



android {
    compileSdkVersion 30
    defaultConfig {
        minSdkVersion 19
        targetSdkVersion 30
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
    }
    lintOptions {
        checkReleaseBuilds false
        abortOnError false
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.3.0'
    implementation 'com.google.android.material:material:1.2.1'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
    testImplementation 'junit:junit:4.13.2'
    implementation "androidx.cardview:cardview:1.0.0"
    implementation "androidx.recyclerview:recyclerview:1.2.1"
    implementation "androidx.recyclerview:recyclerview-selection:1.1.0"
    implementation 'com.github.orangegangsters:swipy:1.2.3@aar'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation "androidx.multidex:multidex:2.0.1"
    implementation 'com.google.android.gms:play-services-ads:15.0.1'
    implementation('com.google.apis:google-api-services-people:v1-rev2-1.21.0')
            {
                exclude module: 'guava-jdk5'
            }

    implementation 'com.squareup.retrofit2:retrofit:2.3.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
    implementation "io.grpc:grpc-okhttp:1.32.2"

}

apply plugin: 'com.google.gms.google-services'

Gradle:

buildscript {
    
    repositories {
        google()
        jcenter()

    }
    dependencies {

          classpath 'com.android.tools.build:gradle:7.1.2'
           classpath 'com.google.gms:google-services:4.3.10'
        classpath 'com.google.firebase:firebase-crashlytics-gradle:2.5.2'

    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

3

Answers


  1. You are actually starting activity two times.
    First time you manually recreated activity and AppCompatDelegate.setDefaultNightMode it also recreate activity to set default theme

    That is why it is looks like activity is being created two times.

    For this what I have done is applied theme in Application class.
    And didn’t created the activity just applied theme

    In My Application Class

     if (preferencesValue!!.getBoolean("theme")) {
                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
            } else {
                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
            }
    

    While changing theme in activity did the same on the change listener of Switch Button

    Where you are creating intent and starting activity you just have to set Theme using AppCompatDelegate.setDefaultNightMode. Do not create Activity again.

    Login or Signup to reply.
  2. set android:configChanges to your activity which restarts after selecting Dark mode

            android:configChanges="...|...|...|...|uiMode|...|..."
    

    uiMode config handles dark mode UI changes on your app.

    refer this documentation

    Example for your activity in manifest

                <activity
                android:name=".SplashActivity"
                android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
                android:launchMode="singleTop"
                android:screenOrientation="sensorLandscape" />
    
    Login or Signup to reply.
  3. Just remove the Intent code because on the SwitchClick system by default recreate your app that’s why no need to call recreate manually. your new code is below

    nightmodeswitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        if (isChecked) {
                                 InıtAplıcation.getInstance().setIsNightModeEnabled(true);
    //or
    // AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
    
                        } else {
                                InıtAplıcation.getInstance().setIsNightModeEnabled(false); 
    //or
    //AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
                        }
    

    and make SharedPrefrence code to save your current boolean of your DayNight Switch. If the problem is not solved yet, let me know

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search