user1744056
user1744056

Reputation:

How can I clear my database when the application is closed?

I need to clear application's database (drop all tables) after closing the application. I decided to implement this in some Activity's onDestroy(). As far as I know all onDestroy() methods are called when application finished running.

But if this is a bad practice - please advise some other way of clearing database when application is closed.

Upvotes: 4

Views: 3161

Answers (3)

npace
npace

Reputation: 4258

Check out this answer.

As for when to drop all tables, best practice would dictate that you do it, or free any other resources, in onPause() if isFinishing() returns true.

Quick note: If you application consists of many activities, you should of course only call this in your root activity's onPause().

Good luck!

Upvotes: 0

Graham Borland
Graham Borland

Reputation: 60681

Would an in-memory database work for you? The database is never saved to persistent storage in the first place, and only exists as long as your process is alive and the database connection is open.

Upvotes: 1

Raghav Sood
Raghav Sood

Reputation: 82553

This is not a good option, as there is no guarantee that onDestroy() will be called when your app shuts down. It may be terminated by the system instantly, in which case you will not be able to clear your data. As stated in the documentation:

Note: do not count on this method being called as a place for saving data! For example, if an activity is editing data in a content provider, those edits should be committed in either onPause() or onSaveInstanceState(Bundle), not here. This method is usually implemented to free resources like threads that are associated with an activity, so that a destroyed activity does not leave such things around while the rest of its application is still running. There are situations where the system will simply kill the activity's hosting process without calling this method (or any others) in it, so it should not be used to do things that are intended to remain around after the process goes away.

Instead, you should make a class that extends Application, and drop your tables in the onCreate() method if they exist, as that method is called only once in an application's lifecycle.

However, if you feel the need to clear data everytime the app stops running, you should reconsider using a database, as they are meant for persistent storage.

Upvotes: 4

Related Questions