Issue
Hello I am trying to figure out a way to destroy my database every time the application starts either by returning from the background or reopen after it was closed. The issue is that when I am trying to run my application for the first time I get a null and my application crushes.
My application: The user is prompt with a login screen and I create the db, move to another activity to perform a query. From this activity the user cannot go back to login, and will be only able to go to the phone home screen. When I will go to the home screen and re open the application I want to wipe out the db and start like it is my first time the user uses the application. I know that this is not actually practical for an application, but this is just for learning.
I tried to do db.close()
and context.deleteDatabase(db.getPath());
in onResume
and onRestart
, but this always crushes my application. I also tried to check that 'db.getPath()!=null' , but this did not help either.
thank you
Solution
Since you are aware that is not the most practical way to use databases I guess I won't bug you for that.
What you want to do is not to call the method to delete the database content during on Resume() or on Restart(), you actually want to call that via on Stop().
The method you want to use is
db.delete(String table, string whereClause, String [] whereArgs);
Passing the name of the table you want to delete, i.e "user_food_database", a whereclause which would be null in your case since you want to delete ALL rows, and null for whereArgs.
Here's the official doc:
"Convenience method for deleting rows in the database.
Parameters table the table to delete from whereClause the optional WHERE clause to apply when deleting. Passing null will delete all rows.
Returns the number of rows affected if a whereClause is passed in, 0 otherwise. To remove all rows and get a count pass "1" as the whereClause. "
You can also call:
deleteDatabase(File pathToDatabase)
in case you have more than one table in your database, but recreating the database itself everytime is expensive, and deleting only the content may result better.
Answered By - daniel_c05
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.