Android: Intent Flag to destroy activity and start new one-ThrowExceptions

Exception or error:

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?

How to solve:

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("");

###

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.

Leave a Reply

Your email address will not be published. Required fields are marked *