How to remove a particular activity from android stack?

             Most common problem face, when developing the application which has the circular flow or you can say loop flow. For E.g. Suppose if you move from A ➜ B ➜ C ➜ D ➜ E then from E ➜ C in C you click on some button and move to C ➜ D.
            Now when you move from E ➜ C ➜ D it will create another copy of C activity and D activity to stack.So whenever you press back button your flow look like this D [New Activity] ➜ C [New Activity ] ➜ E ➜ D [Old Activity] .So to overcome this issue here is the simple solution.


First of all lets create HashMap static object with name of "screenStack".
 

public static HashMap<String, Activity> screenStack;

Now, create method addActivities() which add the activity in screenStack.

// Add activity
public static void addActivity(String activityName, Activity activity)
{
    if (Config.screenStack == null)
        Config.screenStack = new HashMap<String, Activity>();
    if (activity != null)
        Config.screenStack.put( activityName , activity);
}


Now, create method removeActivity() which remove the activity from screenStack.

// Remove Activity
public static void removeActivity(String activityName )
{
   if (Config.screenStack != null && Config.screenStack.size() > 0)
   {
      Activity activity = Config.screenStack.get(activityName);
      if (activity != null)
      {
         activity.finish();
      }
   }
}


Note: From the above code I use "Config.screenStack" in which Config is my class you can use your own class according to your code.

 
If you want to finish all the activity when user leave the application then it is very simple.You can do it using for loop inside for loop you can remove all the activities.

// Close all activities or screens
public static void closeAllScreens()
{
    if (Config.screenStack != null && Config.screenStack.size() > 0)
    {
         for (int i = 0; i < Config.screenStack.size(); i++)
        {
            Activity activity = Config.screenStack.get(i);
            if (activity != null)
           {
               activity.finish();
           }
        }
    }

}

Now, we see how to use this method in your activity.Generally I prefer to add activity when "super.onCreate()" is called.You can choose your own way wherever you want to add your activity.

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    addActivities("DemoActivity", DemoActivity.this)
    setContentView(R.layout.activity_demo);
}

You can also see my stackoverflow answer over here.

Comments

Popular posts from this blog

Upload Image using okHttp

How to blur background images?