starting the same activity with button in android

18,051

Solution 1

Try this :)

Button buttonOne = (Button) findViewById(R.id.button1);
buttonOne.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
       Intent intent = new Intent(MainActivity.this,
                        MainActivity.class);

                startActivity(intent);
}
 });

But i dont understand why you wanna do this :P

Solution 2

The only way to do this is to launch the Intent to that Activity again. But, I don't see why you would want to do that, jut refresh the content of the Activity calling the same activity within that activity.. is redundant and doesn't make sense.

Solution 3

If you just want to reload the activity, for whatever reason, you can use this.recreate(); where this is the Activity.

Share:
18,051
nadeem gc
Author by

nadeem gc

Updated on June 04, 2022

Comments

  • nadeem gc
    nadeem gc about 2 years

    Is it possible to start the same activity on button click. I have a button in my MainActivity and I want that when I click that button the current Activity (MainActivity) restarts (start again) ? Thanks in Advance.

  • nadeem gc
    nadeem gc over 11 years
    Yeah you are right its pretty awkward actually my problem was something else I posted the question yesterday restart camera with button here that is what I wanted.
  • nadeem gc
    nadeem gc over 11 years
    I couldn't get solved this, that's why I thought it other way.
  • JoxTraex
    JoxTraex over 11 years
    Its always better to solve the core problem than patch a symptom.
  • nadeem gc
    nadeem gc over 11 years
    Its working , but when I press backbutton the app crashes why ?
  • Shiv
    Shiv over 11 years
    use finish(); after startActivity(intent); so that it will close current activity and disply the new one
  • Anubhav Mittal
    Anubhav Mittal almost 4 years
    This is never a good practice. Instead you should startActivity() for the same activity and call finish() in the current one.