Scott Miller
Scott Miller

Reputation: 23

Making a Button restart the activity

Ok so I know this may seem simple, I mean I thought it was. But essentially I want the restartActivity method to restart the activity.

First thing I did was create the button and had the line of code in the xml as such. android:onClick="restartActivity"

then my class contains the restartActivity Method as such

public void restartActivity()
{
    Intent intent= new Intent(this, MainActivity.class);
    startActivity(intent);
}

When I try this what ends up happening is the stopped working dialog box. So my question is simply why is this not working. I made sure I made the restart button in the right layout, I checked to make sure all needed references were made. And the android manifest is all correct. It wasn't until I added those two lines it started crashing. I should also mention my target api is 8 and one of the answers suggested was an api 11 or higher. As eclipse "kindly" let me knew.

Upvotes: 0

Views: 9384

Answers (3)

Daniel Conde Marin
Daniel Conde Marin

Reputation: 7742

Activity class already provides this method:

 public void recreate ()

Since: API Level 11 Cause the 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.

So you can do something like this,

public void Restart()
{
   this.recreate();
}

If you are outside of the activity, then simply:

public void Restart(Context ctx)
    {
       //geting activty from context
       Activity a = (Activity)ctx;
       //forcing activity to recrete
       a.recreate();
    }

Upvotes: 5

Raghunandan
Raghunandan

Reputation: 133560

Use Activity context . You are referring to this in on button click. This refers to current context which is button in your case.

 Intent intent= new Intent(ActivityName.this, MainActivity.class);

This will create a new instance of the same activity.

Say you have MainActivity. This is on the back

On button click start the same activity and call finish()

Intent t= new Intent(MainActivity.this,MainActivity.class);
startActivity(t);
finish();

Edit:

In your first activity say on button click

Intent t= new Intent(FirstActivity.this,SecondActivity.class);
startActivity(t);
finish();

In your second Activity on button click

Intent t= new Intent(SecondActivity.this,FirstActivity.class);
startActivity(t);
finish();

Upvotes: 1

Ankitkumar Makwana
Ankitkumar Makwana

Reputation: 3485

your click may Like

 public void restartActivity(View view)
     {
         // do your work Here
         Intent intent= new Intent(currentActivity.this, MainActivity.class);
         startActivity(intent);
     }

Upvotes: 0

Related Questions