Android: Intent Flag to destroy activity and start new one
Asked Answered
B

2

24

So I have a Login Activity This Activity inflates a login.xml layout which has a USER_NAME and PASSWORD EditText Views, when I enter the Username and Password and click the Login Button I start a new Activity.

The new Activity has a Logout button which basically just starts the previous Activity like so:

    Intent loginIntent = new Intent(getActivity(), Login.class);
    loginIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    getActivity().startActivity(loginIntent);

According to the Android Documentation the flag does the following:

http://developer.android.com/reference/android/content/Intent.html#FLAG_ACTIVITY_CLEAR_TOP

If set, and the activity being launched is already running in the current task, then instead of launching a new instance of that activity, all of the other activities on top of it will be closed and this Intent will be delivered to the (now on top) old activity as a new Intent.

The problem is that the Username and Password still appear in the EditText Views after I logout, is there a Flag that destroys the Login activity and just starts a new one or is there a way to reset the fields whenever I logout? Which is the better approach?

Botulism answered 5/11, 2013 at 20:52 Comment(0)
B
30

You have 2 choices:

1 - Kill the login activity after a successful login

Intent loginIntent = new Intent(getActivity(), Login.class);
    loginIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    getActivity().startActivity(loginIntent);
finish();

2 - Empty the values then start new activity

edittext_username.setText("");
edittext_password.setText("");
Backflow answered 5/11, 2013 at 21:2 Comment(1)
I have following flow of activity, 1 -> 2 -> 3 -> 4 -> 5 -> On click of button on 5th Activity , I want to go to Activity 2nd with preserving the data. So basically I want clear 3rd, 4th, 5th activity and go to 2nd with older data which is filled there earlier. As per doc loginIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); is not working. Please help me, I'm really stuck on this issue.Galatians
L
5

If you are supporting only API levels 11+, you should be able to use FLAG_ACTIVITY_CLEAR_TASK. This will finish all existing Activities in all tasks and create a new instance of the Login activity.

Litman answered 5/11, 2013 at 21:2 Comment(2)
I tried that flag but it didn't finish or destroy the Login activity, it seems like it just brought it to the front.Botulism
Interesting. According to the documentation, FLAG_ACTIVITY_CLEAR_TOP should finish and recreate the activity as well (so long as you are not using FLAG_ACTIVITY_SINGLE_TOP in conjunction with it and your launch mode is the default "multiple")Litman

© 2022 - 2024 — McMap. All rights reserved.