Skip to content Skip to sidebar Skip to footer

How To Check If A Db Exists In Android?

I am using Room API to implement a DB in my Android app. It seems that every time I load my app it tries to create the database again and again. Is there any way to restrict this?

Solution 1:

when you create database it call when application start that time their db create.you used to below code in app activity and that activity call in manifest file in application class call like used below code ..

publicclassAppActivityextendsApplication {

AppDatabase db;

@OverridepublicvoidonCreate() {
    super.onCreate();
    db = Room.databaseBuilder(getApplicationContext(), AppDatabase.class, "database-name").build();
}

publicAppDatabasegetDatabase() {
    return db;
}

} and add below line manifest file .. add below line in application tag

        android:name="AppActivity"

Solution 2:

You are using db that is, in fact, a file. You can check, if it exists, this method could be helpful:

privatestaticbooleandoesDatabaseExist(Context context, String dbName) {
    File dbFile = context.getDatabasePath(dbName);
    return dbFile.exists();
}

Solution 3:

You can get count of entities in db (TODO app - example). entities > 0.

classApp: Application() {
    overridefunonCreate() {
        super.onCreate()
        instance = this
        database = Room.databaseBuilder(applicationContext,
            AppDatabase::class.java, "database").build()
    }
    companionobject {
        lateinitvar instance: App
        lateinitvar database: AppDatabase
    }
}

//DB class

@Database(entities = [Task::class], version = 1, exportSchema = false)abstractclassAppDatabase : RoomDatabase() {
       abstractfuntaskDao(): TaskDao
}

//Dao interface

@DaointerfaceTaskDao{
        @Query("SELECT COUNT(id) FROM tasks")fungetTasksCount(): Int
    }

//Model

@Entity(indices = [Index(value = ["title"], unique = true)], tableName ="tasks")
    class Task(
        var title: String = "",
        var description: String = "",
        var date: Date,
        @Embedded 
        var remind: Constants.RemindPeriod = Constants.RemindPeriod.MIN5,
        @Embedded
        var prior: Priority) : Serializable {
        @PrimaryKey(autoGenerate = true)
        var id: Long = 0}

//CheckDB

privatefuncheckDatabaseState() {
        doAsync {
            val db = App.database
            val entityCount = db.taskDao().getTasksCount().or(0)
            isDatabaseNotEmpty = entityCount > 0
        }
    }  

Solution 4:

Try this

if (!db.exists()) {
    // Database does not exist so copy it from assets here
    Log.i("Database", "Not Found");
} else {
    Log.i("Database", "Found");
}

Post a Comment for "How To Check If A Db Exists In Android?"