An SO User
An SO User

Reputation: 25028

Destroy an activity when back button is pressed?

I have an app that allows user to select a txt file from a list and then goes off to the internet to get the contents of that file. All works well except when the user accidentally or deliberately presses the hardware back button to go and see the list again.

Now, when the user clicks a new item from the list (a new file that is), instead of loading a the new file, the app continues off from where it was suspended.I do not want that to happen. I know this is related to the life cycle of the activity.

How do I make sure that it loads the new file rather than continuing from where it left off ?

Upvotes: 0

Views: 19572

Answers (5)

Shaishav Jogani
Shaishav Jogani

Reputation: 2121

Another Method to kill an activity is by calling following method.

@Override
public void onBackPressed() {
    super.onBackPressed();
    finish();
}

Upvotes: 1

Master
Master

Reputation: 2959

To destroy activity on back press, use this code.

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
     //Destroys activity.
     finish();
}

Upvotes: 0

ekjyot
ekjyot

Reputation: 2227

You just need to finish your activity in onBackPressed() method by calling activity.finish();

Upvotes: 0

m0skit0
m0skit0

Reputation: 25874

I suppose you're loading the file in onCreate(). You should do that in onResume() instead.

Android Application Lifecycle

Do not force Activities to close (e.g. use finish()). First, this does not guarantee the Activity will be closed, and second, this is better left to Android to decide.

Upvotes: 4

James McCracken
James McCracken

Reputation: 15766

You can override the onBackPressed method in the activity and call finish() to get the desired outcome.

Upvotes: 0

Related Questions