0

I am new in Android. I have "Menu" activity in which I have ListView with 3 items. When I click on the first item it is opening new Activity ("Play" activity). In that activity I have a button which calls another activity "Result". I am trying to make in "Result" activity onBackPressed method which is return to the "Menu" activity. Here is a code, but this code just return to the "Play" activity:

@Override
public void onBackPressed() {
    // TODO Auto-generated method stub
    finish();
}

Another code just back to "Menu" activity but doesn't close "Result" activity

@Override
public void onBackPressed() {
    // TODO Auto-generated method stub
    Intent intent = new Intent(this , Menu.class);
    startActivity(intent);
}

Please give me some idea how to handle it. Thanks.

David Wasser
  • 93,459
  • 16
  • 209
  • 274
user3079114
  • 69
  • 1
  • 12
  • You can use `intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTROY)` to start your Menu acitivty. BTW you should add android tag. – chartsai Mar 19 '15 at 02:48
  • @Chatea this is a bad suggestion. It will break the standard navigation and probably isn't what the user wants. There are better ways to do this. – David Wasser Mar 19 '15 at 12:10

2 Answers2

1

Do this:

@Override
public void onBackPressed() {
    Intent intent = new Intent(this , Menu.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(intent);
}

This will clear all activities off the stack and return to the Menu Activity.

David Wasser
  • 93,459
  • 16
  • 209
  • 274
  • What `launchMode` type I need while using `Intent.FLAG_ACTIVITY_CLEAR_TOP`? Although I'm not the OP, but I need it. Thanks. – Anggrayudi H Mar 19 '15 at 12:45
  • 1
    @AnggrayudiH `launchMode="singleTop"` – Dzhuneyt Mar 19 '15 at 12:51
  • You can use any launch mode for this. If you use standard launch mode, this will finish the current instance of the launched Activity and then create a new instance of it. If you use "singleTop" launch mode then it won't create a new instance of that Activity, it will just call `onNewIntent()` with the new `Intent`. – David Wasser Mar 19 '15 at 15:13
0

First of all welcome to the android world. You are making two basic and beginner mistakes here. But no problem and no worries by the time you would be good in it.

Now lets talk about your problem. you can achieve this in the following way.

When you are moving from play class to result class by clicking on button you should finish this play class so that it should not be in back stack.

For example:

        playClassBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            Intent intent = new Intent(this , ResultActivity.class);
            startActivity(intent);

            }
        });

and in ResultActivity over ride the onBackPressed method as you have done alread

ghost talker
  • 402
  • 5
  • 15