72

I have created a database for my android app which contains static data and does not require update/delete functionality thus when the app starts, I want to check if the db exists and if not then execute my dbAdapter class. I know its a simple if statement but I was just wondering the most efficient way to query whether the db exists.

Cheers

Gray
  • 115,027
  • 24
  • 293
  • 354
Ally
  • 1,476
  • 3
  • 19
  • 30

7 Answers7

183

I'd rather check the existence of the file directly:

private static boolean doesDatabaseExist(Context context, String dbName) {
    File dbFile = context.getDatabasePath(dbName);
    return dbFile.exists();
}
rds
  • 26,253
  • 19
  • 107
  • 134
84
/**
 * Check if the database exist and can be read.
 * 
 * @return true if it exists and can be read, false if it doesn't
 */
private boolean checkDataBase() {
    SQLiteDatabase checkDB = null;
    try {
        checkDB = SQLiteDatabase.openDatabase(DB_FULL_PATH, null,
                SQLiteDatabase.OPEN_READONLY);
        checkDB.close();
    } catch (SQLiteException e) {
        // database doesn't exist yet.
    }
    return checkDB != null;
}

where DB_FULL_PATH is the path to your database file.

And the reason I am not just checking if a file exists is because it would not tell whether (a) it's an sqlite db file, (b) the file is not corrupt and can actually be read, i.e. due to partial download or however it has been created.

Mathias Conradt
  • 28,420
  • 21
  • 138
  • 192
  • 5
    I tried using this to see if I had to copy the "starter" database from the bundle or just go ahead and load what was there. so I tried using this. but for me this returned true all the time even if there was no database present. – Kit Ramos Dec 16 '13 at 02:54
  • 3
    -1 for using try/catch to perform a normal un-exceptional operation – eddi Nov 16 '14 at 21:43
  • 2
    It's horrible to use a try/catch just to see if something is null...... Why not `checkDB = SQLiteDatabase.openDatabase(DB_FULL_PATH, null, SQLiteDatabase.OPEN_READONLY); if (checkDB == null) {// database doesn't exist yet.}`. I guess it's not your fault, it seems java is plagued with this kind of nonsense... – Kevin Apr 07 '15 at 09:26
  • 1
    Expecting a statement to cause an exception is bad practice. Checking for the database file to exist is the clean and correct approach. – eddiecubed Aug 08 '15 at 23:56
  • 2
    Checking only for the database file existence does not cover everything. So you want to let the user run into an exception, such as the SQLiteException? You will need to catch it in any case sooner or later, unless you want to cause an ANR in your app. Above method checks whether the database is available and ready to work, not only checking its existence. How do you handle the case where the database exists but cannot be read / parsed due to whatever reason, other than by handling the exception? – Mathias Conradt Aug 10 '15 at 06:19
  • 1
    @eddi The operation is not un-exceptional, it can throw an SQLiteException. – Mathias Conradt Aug 10 '15 at 06:20
  • This is a helper method that encapsulates many use-cases for a potential failure, but for cases where you just want to tell the user "the database isn't ready or missing", this is sufficient. It means, you need to check whether the database exists AND can be parsed/read, otherwise you will need to check it at a later stage anyway. – Mathias Conradt Aug 10 '15 at 06:21
  • 3
    The question was to check if the database exists. Not if it can be opened and accessed. Based on the description, the database is coming from the assets folder. Which this would run at start up, and check at first run if the database exists. And as you said, this catch could be the result of other issues, not only that the database does not exist. However using this will leave the application blind to what went wrong. This is bad programming technique. – eddiecubed Aug 10 '15 at 14:34
4

When you initialize the below class with:

mOpenHelper = new DatabaseHelper(getContext());

That will automatically create the database if it is not present. It also allows you upgrade the database by changing the DB_VER to a higher number.

Then so you are able to query the database use:

 SQLiteDatabase db = mOpenHelper.getWritableDatabase();

the above gets you db.query() & db.insert() etc methods.

private static class DatabaseHelper extends SQLiteOpenHelper {

    private static final String DB_NAME = "db_name.db";
    private static final int DB_VER = 1;

    public DatabaseHelper(Context context) {
        super(context, DB_NAME, null, DB_VER);

    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL("CREATE TABLE table_name (" + "_id INTEGER PRIMARY KEY, "
                + " column_name_2 TEXT );");


                .execSQL("INSERT INTO table_name "
                        + "(column_name_2) "
                        + "VALUES " + "('hello world');");


    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        Log.w(TAG + "Upgrading database from version " + oldVersion + " to "
                + newVersion + ", which will destroy all old data");
        try {
            db.execSQL("DROP TABLE IF EXISTS table_name");
            onCreate(db);

        } catch (SQLException e) {
            Log.e(TAG + "getting exception "
                    + e.getLocalizedMessage().toString());
        }
    }

}
Andro Selva
  • 53,910
  • 52
  • 193
  • 240
userdelroot
  • 197
  • 1
  • 5
2

I tried the version as provided by Mathias Conradt but I found that to simply check if DB != null is insufficient. I have amended to this:

         /**
         * Check if the database exist and can be read.
         *
         * @return true if it exists and can be read, false if it doesn't
         */
        private boolean checkDataBase(String InDBFile) {
            SQLiteDatabase checkDB = null;
            boolean res = false;
            try {
                checkDB = SQLiteDatabase.openDatabase(InDBFile, null,
                        SQLiteDatabase.OPEN_READONLY);
                res = (checkDB.getVersion() > 0);
                checkDB.close();
            } catch (SQLiteException e) {
                // database doesn't exist yet.
                Log.e("checkDataBase", "Selected file could not be opened as DB.");

                res = false;
            }
            return res;
        }
2

it's simple: Open your database in try block with path of da databse like:

try{
   SQLiteDatabase   dbe = SQLiteDatabase.openDatabase("/data/data/bangla.rana.fahim/databases/dictionary", null,0);
            Log.d("opendb","EXIST");
            dbe.close();
            }

if an exception occurs then database doesn't exit so create it:

catch(SQLiteException e){
                Log.d("opendb","NOT EXIST");

            SQLiteDatabase db = openOrCreateDatabase("dictionary", MODE_PRIVATE, null);
                    db.execSQL("CREATE TABLE IF NOT EXISTS LIST(wlist varchar);");

                    db.execSQL("INSERT INTO LIST VALUES('খবর');");
                    db.execSQL("INSERT INTO LIST VALUES('কবর');"); //whatever you want
                 db.close();
}

that's it you are done :)

Imran Rana
  • 11,899
  • 7
  • 45
  • 51
0

Create a global database helper class object in your main activity. In the MainActivity's onCreate() function try this:

//global database helper variable

DatabaseHelper dbh;

//in the onCreate()

if(dbh.getReadableDatabase()!=null)
//view the list

else
//create db
himanreddy
  • 9
  • 1
  • 2
  • 1
    This doesn't answer the question. It would with the code of the DatabaseHelper. – rds Feb 19 '18 at 15:39
0

I have found an even simpler solution:

context.databaseList().contains("table_name")

Lina Shyshova
  • 546
  • 5
  • 12