Home » Android » android – Go back to previous screen without creating new instance

android – Go back to previous screen without creating new instance

Posted by: admin June 15, 2020 Leave a comment

Questions:

enter image description here

As explained in image, flow is something like this. So whenever user click on logo button Activity A should be called. As simple solution we can use this method…

Intent intent = new Intent(activity, activityToStart);
startActivity(intent);

But this activity will create a new activity for my app. but I need to call the same instance of the activity as we move forward in flow diagram. from Activity A to B and then again on B can be called easily by callingfinish() but from Activity C or D, how to come back to A.

I am running out of ideas but not getting any fruitful result. Please help me if you have any suggestion or at any place i am going wrong. Thanks in advance.

How to&Answers:

To Come Back from D to A, use Intent Flags.

Intent intent = new Intent(activity, activityToStart);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
startActivity(intent);

FLAG_ACTIVITY_CLEAR_TOP, will instead of creating new activity, it will invoke the activity on the stack, and will pop all the activities over the activity being invoked.

Answer:

By making Activity A a “SingleTask” you can achive this. When a Activity is in the SingleTask on clicking the Home button the other activites will be removed from the stack.

Refer these link’s for more info on Android Activites…

Link 1 – Android Fundamentals

Link 2 – Another Similar Question

Answer:

Use ViewFlipper to go and back between different window in the same activity.

ViewFlipper vf = (ViewFlipper) findViewById( R.id.view_flipper);

To go to the next window

vf.showNext();

To go to the previous window

vf.showPrevious();

Answer:

Instead of Using

Intent intent = new Intent(activity, activityToStart);
startActivity(intent);

Use

Intent intent = new Intent(activity, activityToStart);
startActivityforResult(intent,1234);

This will make Sure that The Activity A is not Killed and when You finish Your Activity C,Activity A will get Resumed.

Note :- Whenever You create A new Activity,without finishing(Exiting) the Host Activity,The Host Activity is Saved On the Stack in LIFO order

LIFO:- Last In First Out

Answer:

I am not sure,this is right way or not,but you can give it a try!

You can finish() current activity when you open the new one starting from Activity-B.

i.e.

To open Activity-C => finish Activity-B and start Activity-C

To open Activity-D => finish Activity-C and start Activity-D

now when you will press back,Activity-A will open.