Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Does SQLite Database Exist? [duplicate]

How can I quickly check if a database exists in Android?

(not a Table - the entire database)

like image 624
yydl Avatar asked Jun 21 '11 03:06

yydl


Video Answer


2 Answers

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!

like image 60
Mudassir Avatar answered Oct 15 '22 14:10

Mudassir


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
}
like image 34
Kit Ramos Avatar answered Oct 15 '22 14:10

Kit Ramos