Is there a better way to finish the activity from another activity?

Viewed 2607

I have 3 activities FirstActivity, SecondActivity and ThirdActivity. FirstActivity leads to SecondActivity which leads to ThirdActivity. I would like to be able to move back and forth between FirstActivity and SecondActivity , FirstActivity and ThirdActivity.

Here is what I have implemented :

FirstActivity :

In FirstActivity I have an onClick method 'goToSecondActivity', which starts SecondActivity

 public void goToSecondActivity(View view){
        Intent i = new Intent(this, SecondActivity.class);
        final EditText firstText = (EditText) findViewById(R.id.firstText);
        String userMessage = firstText.getText().toString();
        if(!"".equals(userMessage))
        i.putExtra("firstMessage",userMessage);

        startActivity(i);
    }

enter image description here

SecondActivity :

In SecondActivity again I have an onClick method 'goToThirdActivity', which starts ThirdActivity

public void goToThirdActivity(View view){
        Intent i = new Intent(this , ThirdActivity.class);
        startActivity(i);
    }

enter image description here

ThirdActivity :

In ThirdActivity I have two onClick method 'backToFirstActivity' and 'backToPreviousActivity' on two different buttons

enter image description here

On ThirdActivity when I click On 'Back To First Activity' button , I want to go back to the FirstActivity.

What I have Done :

SecondActivity :

I have declared static variable

static SecondActivity secondActivityMain;

And assign it in onCreate method :

protected void onCreate(Bundle savedInstanceState) {
       ---
       ---
        secondActivityMain = this;
       ---
       ---

}

ThirdActivity :

Using static variable finishes the SecondActivity "SecondActivity.secondActivityMain.finish();"

 public void backToFirstActivity(View view) {
        Toast.makeText(getApplicationContext(), "Third: finished second activity ",
                Toast.LENGTH_SHORT).show();

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                SecondActivity.secondActivityMain.finish();
                ThirdActivity.this.finish();
            }
        }, 2000);

    }

My Questions Are :

1. Is there a better way to finish the activity from another activity?

2. Is this way is correct?

2 Answers
Related