12

My launcher activity i.e. MainActivity is getting instantiated twice while using AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES) which is leading to two network calls and making weird behavior.

Is there any to control this and make to initialize only once?. I've tried using launchMode = "singleTop" and "singleInstance"

 override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
    mRequestQueue = Volley.newRequestQueue(this)
    Log.e(TAG,"Skillet")
    loadStateData()
    initializeListeners()
}
Buddy Christ
  • 1,364
  • 8
  • 22
shahooo
  • 563
  • 4
  • 14
  • 3
    why are you do that in activity, but not in the App class? `setDefaultNightMode` always do recreation of activity. because your configuration changed. Maybe you just move your api call in another activity lifecycle method? – Oleg Skidan Apr 09 '20 at 18:54

3 Answers3

21

Found a solution after trying a few of my practices

override fun onCreate(savedInstanceState: Bundle?) {
    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    }

Call dark mode function before super of onCreate()

It will prevent instantiating activity twice

shahooo
  • 563
  • 4
  • 14
4

Activities are restarted in some scenarios like an orientation change, there is nothing wrong with this.

Instead of preventing the activity from restarting, which is part of its lifecycle, another thing that you could do and is what I encourage you to do is to use a ViewModel to handle this tasks as it is recomended in the recommended app architecture so that when your activity gets restarted and asks for its ViewModel:

viewModel = ViewModelProviders.of(this).get(MainActivityViewModel::class.java)

it reuses the same ViewModel and the tasks continue as if nothing has happened.

Actually, if you want to follow that architecture the tasks should be done in a repository, but the ViewModel should be in charge of it and it does not be recreated when the activity is restarted.

I recommend you to do the Android Kotlin Fundamentals 05.1 codelab about this.

jeprubio
  • 17,312
  • 5
  • 45
  • 56
1

Found a solution for those who use "binding"

It's funny but works:

protected void onCreate(Bundle savedInstanceState) {

    sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);

    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);

    binding = ActivityMainBinding.inflate(getLayoutInflater());
    super.onCreate(savedInstanceState);
    setContentView(binding.getRoot());

    binding = ActivityMainBinding.inflate(getLayoutInflater());
    setContentView(binding.getRoot());
    } 
Tal Vaknin
  • 71
  • 1
  • 3