| | |
| | | import android.content.Context |
| | | import android.os.Environment |
| | | import androidx.room.Room |
| | | import com.dayu.general.activity.BaseActivity |
| | | import androidx.room.migration.Migration |
| | | import androidx.sqlite.db.SupportSQLiteDatabase |
| | | import java.io.File |
| | | |
| | | class BaseDaoSingleton { |
| | |
| | | @JvmField |
| | | val SqlitePath: String = |
| | | Environment.getExternalStorageDirectory().absolutePath + File.separator + ".dayu" + File.separator + "data" + File.separator |
| | | |
| | | // 数据库迁移策略:从版本3迁移到版本4 |
| | | private val MIGRATION_3_4 = object : Migration(3, 4) { |
| | | override fun migrate(database: SupportSQLiteDatabase) { |
| | | // 这里不需要实际的数据库结构修改,因为我们只是更新了Room版本 |
| | | // 如果需要修改数据库结构,可以在这里添加 ALTER TABLE 语句 |
| | | } |
| | | } |
| | | |
| | | fun getInstance(context: Context): AppDataBase { |
| | | if (baseDao == null) { |
| | | baseDao = Room.databaseBuilder<AppDataBase>( |
| | |
| | | } |
| | | return baseDao as AppDataBase |
| | | } |
| | | fun getAsynchInstance(context: Context?): AppDataBase? { |
| | | fun getAsynchInstance(context: Context): AppDataBase { |
| | | if (AsynchBaseDao == null) { |
| | | AsynchBaseDao = Room.databaseBuilder<AppDataBase>( |
| | | context!!, |
| | | AppDataBase::class.java, |
| | | SqlitePath + "ConfigurationData_generalV1" |
| | | ).build() |
| | | synchronized(this) { |
| | | if (AsynchBaseDao == null) { |
| | | AsynchBaseDao = Room.databaseBuilder( |
| | | context.applicationContext, |
| | | AppDataBase::class.java, |
| | | "GeneralLibrary.db" |
| | | ) |
| | | .addMigrations(MIGRATION_3_4) // 添加迁移策略 |
| | | .build() |
| | | } |
| | | } |
| | | } |
| | | return AsynchBaseDao |
| | | return AsynchBaseDao as AppDataBase |
| | | } |
| | | |
| | | // 销毁数据库实例 |
| | | fun destroyInstance() { |
| | | AsynchBaseDao = null |
| | | } |
| | | } |
| | | |