0

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.

Hartaithan.
  • 326
  • 3
  • 14

3 Answers3

1

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();
        }
    }
Akshay
  • 752
  • 1
  • 8
  • 25
1

you can't compare two Strings like this in your if condition

checkRun == "YES"

these are two separated instances of String, so they never be equal in the this meaning (== - same object)

use this instead

"YES".equals(checkRun)

equals will compare "content" of compared objects, in String case it will compare text

snachmsm
  • 17,866
  • 3
  • 32
  • 74
-3

use onResume Method

 @Override
    public void onResume() {
        super.onResume();  // Always call the superclass method first
  
    }