1

I'm working on an android application and in the application I have a couple buttons that let user to pass to another activity. Now the way I'm doing the transitions between this Intents is like below:

    Intent intent = new Intent(this,user_area.class);
    intent.putExtra("user",user_name.getText().toString());
    startActivity(intent);

With the above content I start an activity and from that activity I'm getting back to the MainActivity using this code:

    Intent intent = new Intent(context,MainActivity.class);
    startActivity(intent);

But i suspect this cause memory to be over used because I'm not actually getting back to the Main Activity that created when application started, I'm just creating another instance of MainActivity I guess. Is this really as i thought and if it is how can I get back to the activity that created in the beginning or if I can't do such thing how can I make app to let the previous activity go?

Ahmet Urun
  • 169
  • 3
  • 18

3 Answers3

2

Passing an intent to startActivity() will create a new instance of the activity and add it to the front of the stack. So:

Intent intent = new Intent(context,MainActivity.class);
startActivity(intent);

is basically asking to create a new instance. If you want to go back to the activity just before the current one, call either:

finish();

Or,

super.onBackPressed();
Shaishav
  • 5,282
  • 2
  • 22
  • 41
1

In your solution you just have to press back button and you'll be back in first activity. If you want to close it and after open new instance like you are doing in second activity just add

finish();

at the end of

Intent intent = new Intent(this,user_area.class);
intent.putExtra("user",user_name.getText().toString());
startActivity(intent);
mariusz-
  • 209
  • 1
  • 10
  • Mariano thanks for fast respond. As you said I can get to the MainActivity with just pressing back button but I don't want to get back to the MainActivity by doing that, I want to get back with a button click action. Is there a way to achieve that and at the same time not creating a new activity? – Ahmet Urun Aug 14 '16 at 09:19
1

You just need to call finish(); method

Intent intent = new Intent(this, DestinationActivity.class);
startActivity(intent);
finish();