androidkotlinrecreate

How do I recreate the activity only once after opening the application?


How do I recreate the activity only once after opening the application?

I tried to do this, but it didn't work. Endlessly recreate()

refreshLang() in onCreate

private fun refreshLang() {
    PreferenceManager.getDefaultSharedPreferences(this).apply {
        val checkRun = getString("FIRSTRUN", "DEFAULT")
        if (checkRun == "YES") {
            PreferenceManager.getDefaultSharedPreferences(this@MainActivity).edit().putString("FIRSTRUN", "NO").apply()
            recreate()
        }
    }
}

and SharPref.putString("FIRSTRUN", "YES").apply() in onDestroy to make it work again the next time you run it.


Solution

  • Please refer: Activity class recreate()

    It create new instance and initiates fresh activity lifecycle.

    So when you call recreate() it will call onCreate() and will go in endless loop.

    You have add some condition to avoid this overflow.

    Edit:

    Use .equals instead of ==

    if ("YES".equals(checkRun)) {
       PreferenceManager.getDefaultSharedPreferences(this@MainActivity).edit().putString("FIRSTRUN", "NO").apply()
       recreate()
    }
    

    I suggest you not to use recreate(). It will call onCreate and onDestory().

    Refer below code.

    protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            
            boolean recreateRequested = true;
            Intent currentIntent = getIntent();
            if (currentIntent.hasExtra("recreateRequested")){
                recreateRequested = currentIntent.getBooleanExtra("recreateRequested", true);
            }
            if (recreateRequested) {
                Intent intent = new Intent(this, MyActivity.class);
                intent.putExtra("recreateRequested", false);
                startActivity(intent);
                finish();
            }
        }