17

I know this is probably extremely simple, but I just can not figure it out.

I'm trying to reload/recreate an activity after an action. I know I could just use:

Intent intent = getIntent();
finish();
startActivity(intent);

But in reading through answers on the site I'm told to use 'recreate()' after 11 api. Any help would be appreciated, thanks!

James Jones
  • 572
  • 1
  • 6
  • 17

3 Answers3

31

While using the recreate method works by doing

this.recreate()

It was only added in API level 11. If you want to include more devices you can check the API level and implement both the recreate method as well as

Intent intent = getIntent();
finish();
startActivity(intent);

You can use both by making an if statement like...

if (android.os.Build.VERSION.SDK_INT >= 11) {
    //Code for recreate
    recreate();
} else {
    //Code for Intent
    Intent intent = getIntent();
    finish();
    startActivity(intent);
}
SapuSeven
  • 1,473
  • 17
  • 30
Tristan
  • 3,530
  • 3
  • 30
  • 39
  • Same comment above - Incredibly simple, thanks so much! Thanks also for the additional explanation and if checking (employing your specifically in my project). – James Jones Apr 18 '15 at 21:20
  • 1
    I'm performing some task inside a thread. I can't call recreate() method? – ManishNegi Jul 20 '17 at 10:00
  • Not entirely sure what you mean? Have you tried mContext.recreate()? – Tristan Jul 20 '17 at 15:05
  • how about recreate app without saved state? . For ex: user selects Date(game level) -> save it to SharedPref -> recreate activity based on updated SF value dismissing old state. (will create new question but I am afraid I will be bounce back this or similar thread) – kiranking Apr 05 '19 at 19:34
2

this.recreate() is all it takes. Stick that code inside a method that lives in the activity you want to reload. I have a project where this is tied to a button click but you can use it however you need to.

Chamatake-san
  • 551
  • 3
  • 10
2

I'm a bit confused by your question, you yourself answered the question in your answer. Call the method recreate directly...

From the documentation for recreate():

Cause this Activity to be recreated with a new instance. This results in essentially the same flow as when the Activity is created due to a configuration change -- the current instance will go through its lifecycle to onDestroy() and a new instance then created after it.

Call recreate() from within the activity code instead of

Intent intent = getIntent();
finish();
startActivity(intent);

to restart the activity (after API 11 that is).

See this answer for a more generic recreate routine that works even for before API/SDK 11.

Community
  • 1
  • 1
initramfs
  • 8,275
  • 2
  • 36
  • 58