Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.


2 Answers

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.

like image 89
Raghav Sood Avatar answered Oct 22 '25 21:10

Raghav Sood


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.

like image 26
Graham Borland Avatar answered Oct 22 '25 22:10

Graham Borland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!