Query if Android database exists!

AndroidDatabase

Android Problem Overview


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

Android Solutions


Solution 1 - Android

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();
}

Solution 2 - Android

/**
 * 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.

Solution 3 - Android

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());
		}
	}

}

Solution 4 - Android

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 :)

Solution 5 - Android

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;
		}

Solution 6 - Android

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

Solution 7 - Android

I have found an even simpler solution:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAllyView Question on Stackoverflow
Solution 1 - AndroidrdsView Answer on Stackoverflow
Solution 2 - AndroidMathias ConradtView Answer on Stackoverflow
Solution 3 - AndroiduserdelrootView Answer on Stackoverflow
Solution 4 - AndroidImran RanaView Answer on Stackoverflow
Solution 5 - AndroidHolger BehrensView Answer on Stackoverflow
Solution 6 - AndroidhimanreddyView Answer on Stackoverflow
Solution 7 - AndroidLina ShyshovaView Answer on Stackoverflow