How can I quickly check if a database exists in Android?
(not a Table - the entire database)
Open your database and catch the SQLitException which will be thrown in case if database doesn't exist. Note that, you should not call the openOrCreateDatabase()
method. See this post for details; Query if Android database exists!
My way to check to see if your database exists is to open a file handle on it and see if the file exists. from my experience using "openOrCreateDatabase()" function will not throw an error if the db doesn't exist. take a look a the name "Open OR Create Database". meaning if there's no db to open it'll just make a new one, so regardless of if there was one before there is one now. I think the only time you'll get an error thrown is if it can't do either. which from what the guy said I don't believe is what they are trying to test for, I think he wanted his program to know if the db was already there before hand, and not to automatically create a blank one if there wasn't. so Since all db's are stored as files, the first parameter in that open database command is the file name. So I think the best option is to check to see if the db file exists like so:
File dbtest = new File("/data/data/yourpackagename/databases/dbfilename");
//If you have Context, you could get the Database file using the following syntax
//File dbtest = getApplicationContext().getDatabasePath("dbfilename.db");
if(dbtest.exists())
{
// what to do if it does exist
}
else
{
// what to do if it doesn't exist
}
精彩评论