-3

In my application I have 6 activities like 1->2->3->4->5->6. In 6th activity user can choose any activity(I am launching with intent). Means he can choose 1 or 2 or 3 or 4 or 5. Now when I press back button it is coming back to 6th activity again(which I do not want).

ex: I have executed like this 1->2->3->4->5->6. Now I am in 6th activity. Here I have button, when I press it, it launched 4th activity. My code is like this on button click.

Intent intent = new Intent(MainScreen.this, UniversitiesScreen.class);
startActivity(intent); 

So now I am in 4th activity. When I press back button it taking me to 6th activity(which I came from) instead 3rd activity(what I am expecting). Can any one help me to handle this type of navigation.

Pankaj
  • 7,908
  • 6
  • 42
  • 65
Moses
  • 333
  • 1
  • 6
  • 19

2 Answers2

1

Simple answer is edit your onBackPressed method in every activity... For example, Write in 4th activity like this

 @override
    public void onBackPressed(){
    Intent in = new Intent(this, ThirdActivity.class);
    startActivty(in);
    finish();
    }

Please check the context that you are passing to intent. Every activity is different so pass the activity context from where you are calling another activity. If my guess is true Mainscreen.this is first activity, and if you call fifth activity from fourth activity, give intent as

Intent in = new Intent(FourthActivity.this,FifthActivity.class);
startActivity(in);     
finish();

And you are not saving any data in backstack and you are going back manually...

0

The best way is to use the NavUtils.navigateUpFromSameTask(this) function in your activity. For this you need to define the parent activity in the manifest for each activity so when you are in the 4th activity then the parent activity is the 3rd activity.Then when you click on back or navigate up you end up in the parent activity i.e. from 4th to the 3rd.

Take a look at this http://developer.android.com/training/implementing-navigation/ancestral.html

Look at the manifest and then the Navigate up to parent task section

This will also help in returning to the same state of the 3rd activity from the 4th activity.

Yogesh
  • 444
  • 4
  • 12