I'm trying to have a prepopulated database with my Android app but I'm finding with the database inspector that the table is empty. I found it was working before I added a "favourite" column but now it doesn't work (also removing "favourites" still doesn't make it work, so I had changed other things too).
#Entity
#Parcelize
data class Quote (
#PrimaryKey(autoGenerate = true) val id: Int,
val quote: String,
val author: String,
val genre: String,
val favourite: Int
) : Parcelable
#Database(entities = [Quote::class], version = 10)
abstract class QuoteDatabase : RoomDatabase() {
abstract fun quoteDao(): QuoteDao
}
private lateinit var INSTANCE: QuoteDatabase
fun getDatabase(context: Context) : QuoteDatabase {
synchronized(QuoteDatabase::class.java) {
if (!::INSTANCE.isInitialized) {
INSTANCE = Room.databaseBuilder(context.applicationContext,
QuoteDatabase::class.java,
"quotes")
.createFromAsset("quotes.db")
.fallbackToDestructiveMigration()
.build()
}
return INSTANCE
}
}
// Exported Schema
"tableName": "Quote",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `quote` TEXT NOT NULL, `author` TEXT NOT NULL, `genre` TEXT NOT NULL, `favourite` INTEGER NOT NULL)"
It looks like my schema is okay and I had even exported the schema from Room and it looks like it matches my current table schema. My file is also directly in "assets/quotes.db" (doesn't have any subfolders like "database"). The DB is being generated within the emulator from device file inspector. But database inspector is showing nothing. Even when I copy the file from the device and open it with DB Browser there's nothing in there. And of course, my prepopulated database has data in it.
What's going wrong?
Related
I am new to SQLite and trying to create an SQLite database. Still, the problem is that even though I am using writabledatabase before inserting the data in the addData() method I still get the error "no such table". I don't know where the bug is.
This is the code for the database class.
Of course, I am creating DBHelper in the MainActivity and I pass this as the context.
class DBHelper(context: Context, factory: SQLiteDatabase.CursorFactory?) : SQLiteOpenHelper(context, DATABASE_NAME, factory, DATABASE_VERSION)
{
private val SQL_CREATE_ENTRIES = "CREATE TABLE $TABLE_NAME (" + "${BaseColumns._ID} INTEGER, " + "$COLUMN_NAME_CHAPTER TEXT," + "$COLUMN_NAME_VERSE TEXT, " + "$COLUMN_NAME_NUMBER INTEGER)"
private val SQL_DELETE_ENTRIES = "DROP TABLE IF EXISTS $TABLE_NAME"
override fun onCreate(db: SQLiteDatabase) {
Log.i("testDatabase", "create")
db.execSQL(SQL_CREATE_ENTRIES)
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
db.execSQL(SQL_DELETE_ENTRIES)
onCreate(db)
}
fun addData(name: String, content: String, number: Int) :Boolean
{
val values = ContentValues().apply {
put(COLUMN_NAME_CHAPTER, name)
put(COLUMN_NAME_VERSE, content)
put(COLUMN_NAME_NUMBER, number)
}
val db = writableDatabase
val newId = db?.insert(TABLE_NAME, null, values)
db.close()
return newId?.toInt() != -1
}
companion object {
const val DATABASE_VERSION = 1
const val DATABASE_NAME = "FeedReader.db"
const val TABLE_NAME = "versesBookmarked"
const val COLUMN_NAME_CHAPTER = "chapter"
const val COLUMN_NAME_VERSE = "verse"
const val COLUMN_NAME_NUMBER = "number"
}
}
This is the error I am getting:
E/SQLiteLog: (1) no such table: versesBookmarked in "INSERT INTO versesBookmarked(number,verse,chapter) VALUES (?,?,?)"
E/SQLiteDatabase: Error inserting number=0 verse=بِسْمِ اللَّهِ الرَّحْمَٰنِ الرَّحِيمِ chapter=الفاتحة
android.database.sqlite.SQLiteException: no such table: versesBookmarked (code 1 SQLITE_ERROR): , while compiling: INSERT INTO versesBookmarked(number,verse,chapter) VALUES (?,?,?)
There is nothing wrong with your code, although a few things that you might wish to consider.
You code as it is (with the exception of not closing the database) runs fine and the resultant database, using App Inspection shows:-
As such your issue is probably that you have run the code, and it failed when creating the table, and then you have corrected the code and then rerun.
The Very Likely Fix
If the above is true then the Fix is simple, uninstall the App and rerun.
Explanation
The reason is that even though the table creation may have failed, it would have done so in the onCreate method. This method is run after the database itself has been created (i.e. an empty database as far as app specific tables are concerned).
As the database exists albeit without your user defined tables, the onCreate method will never run again as the database exists (and hence why the table not found). So the only way to get the onCreate method to run automatically is to delete the database, the simplest way is to uninstall the App.
Additional
I would suggest the following changes before rerunning though
change that _id column from just INTEGER to INTEGER PRIMARY KEY, thus when inserting the _id column will be assigned a unique value that can be used to identify the row (otherwise null is of little use even though each value is considered unique it cannot be used to uniquely identify a row).
so private val SQL_CREATE_ENTRIES = "CREATE TABLE $TABLE_NAME (" + "${BaseColumns._ID} INTEGER PRIMARY KEY, " + "$COLUMN_NAME_CHAPTER TEXT," + "$COLUMN_NAME_VERSE TEXT, " + "$COLUMN_NAME_NUMBER INTEGER)"
do not close the database, closing the database means that the next use has to open the database which is relatively heavy in resource usage. e.g. use:-
val newId = db?.insert(TABLE_NAME, null, values)
//db.close() /*<<<<<<<<<< COMMENTED OUT */
Have null as the default CursorFactory (you probably don't want a custom CursorFactory)
so class DBHelper(context: Context, factory: SQLiteDatabase.CursorFactory?=null) : SQLiteOpenHelper(context, DATABASE_NAME, factory, DATABASE_VERSION)
Consider using a singleton approach by adding the following in the companion object:-
#Volatile
var instance: DBHelper?=null
fun getInstance(context: Context): DBHelper {
if (instance==null) {
instance = DBHelper(context)
}
return instance as DBHelper
}
so wherever you use dbHelper = Dbhelper.getInstance(this), you retrieve the same single instance of the database. Whilst using dbHelper = DBHelper(this) will create a new instance.
Using the above with the following in an Activity (when running after afresh install):-
class MainActivity : AppCompatActivity() {
lateinit var dbHelper: DBHelper
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//dbHelper = DBHelper(this) without the singleton
dbHelper = DBHelper.getInstance(this)
dbHelper.addData("بِسْمِ اللَّهِ الرَّحْمَٰنِ الرَّحِيمِ","الفاتحة ",0)
}
}
Will:-
result in the log including D/HostConnection: createUnique: call
result in the database being:-
2.1
2.1 Notice how the _id has the value of 1 as opposed to null, and it will be the only row that has an _id of 1
If the App is run again (without uninstalling it) then :-
i.e. a second row has been added, and the _id of the second row is 2
I have a database in Android with Room from which I have deleted a column. I was doing the migration, and I saw that it was not as simple as doing a DROP of the deleted column.
Then I have seen that I have to take a series of steps, creating a provisional table that will later be the new table with the deleted column, but the problem is that this table contains a field that is a String Array that I don't know how to declare in SQL.
#Entity(tableName = "recipe_table")
data class RecipesDb(
#PrimaryKey
#ColumnInfo(name = "id")
val id: Long,
#ColumnInfo(name = "name")
val name: String,
#ColumnInfo(name = "category")
val category: List<String>,
#ColumnInfo(name = "isRecommended")
val isRecommended: Boolean,
#ColumnInfo(name = "images")
val images: List<String>,
#ColumnInfo(name = "ingredients")
val ingredients: List<String>,
#ColumnInfo(name = "date")
val date: Long,
#ColumnInfo(name = "time")
val time: Int,
#ColumnInfo(name = "difficult")
val difficult: String,
#ColumnInfo(name = "originalUrl")
val originalURL: String? = null,
#ColumnInfo(name = "author")
val author: String,
#ColumnInfo(name = "siteName")
val siteName: String
)
And now I have removed the ingredients column. I wanted to do something like this:
private val MIGRATION_3_2 = object : Migration(3,2) {
override fun migrate(database: SupportSQLiteDatabase) {
//Drop column isn't supported by SQLite, so the data must manually be moved
with(database) {
execSQL("CREATE TABLE Users_Backup (id INTEGER, name TEXT, PRIMARY KEY (id))")
execSQL("INSERT INTO Users_Backup SELECT id, name FROM Users")
execSQL("DROP TABLE Users")
execSQL("ALTER TABLE Users_Backup RENAME to Users")
}
}
}
But when I declare the new temporary table User_Backup, I have no idea how to specify that one of the fields is an Array. In the end I was able to do it with Room's AutoMigrations and creating an interface, but I would like to know how to do it this way as well.
The simple way is to compile the code (Ctrl+F9) with the changed #Entity annotated classes in the list of entities of the #Database annotation.
Then look at the generated java (visible via the Android View in Android Studio). There will be a class that is the same name as the #Database annotated class but suffixed with _Impl.
In this class there will be a method that is named createAllTables, This includes the SQL that room uses for creating the tables.
Just copy and paste the appropriate SQL and then change the table name, this will not only use the correct type but also apply the correct column constraints that Room expects.
I would suggest
Adding an execSQL("DROP TABLE IF EXISTS the_backup_table_name;") before you create a table (just in case it already exists)
And instead of using execSQL("DROP TABLE Users") to use execSQL("DROP TABLE IF EXISTS the_original_table_name")
Personally I always RENAME the table name of the original, then RENAME the new table and then finally DROP the renamed original.
I would use:-
private val MIGRATION_3_2 = object : Migration(3,2) {
override fun migrate(database: SupportSQLiteDatabase) {
//Drop column isn't supported by SQLite, so the data must manually be moved
with(database) {
execSQL("DROP TABLE IF EXISTS Users_Backup")
execSQL("CREATE TABLE IF NOT EXISTS ....) //<<<<< SEE NOTES BELOW, the SQL MUST BE CHANGED.
execSQL("INSERT INTO Users_Backup SELECT id, name FROM Users")
execSQL("ALTER TABLE Users RENAME TO Old_Users")
execSQL("ALTER TABLE Users_Backup RENAME to Users")
execSQL("DROP TABLE IF EXISTS Old_users")
}
}
}
note .... indicates that the SQL is copied from the generated java and that the table name is changed from Users to Users_Backup
The first line will drop the Uers_backup just in case it happens to exist, it's just a little less likely to fail under unusual circumstances.
Rather than dropping the Users table before the RENAME of the Users_Backup to Users. The 4th execSQL changes the name of the Users table, so should there be an issue with changing the Users_Backup table to be the Users table, then the original Uers table is available as Old_users.
When all has been complted then the original Users table, now named Old_Users is then dropped.
These are all just a little safer/secure.
I'm trying to migrate a new database version. The only thing changed is an added column. I always get the following error:
android.database.sqlite.SQLiteException: no such table: database-notes (code 1 SQLITE_ERROR): , while compiling: ALTER TABLE 'database-notes' ADD COLUMN image TEXT
I don't understand why I get this exception, because my table is named database-notes as written in the .build() call.
This is my database class:
#Database(
version = 2,
entities = [Note::class],
exportSchema = true)
abstract class AppDatabase : RoomDatabase() {
abstract fun noteDao(): NoteDAO
companion object {
fun build(context: Context) = Room.databaseBuilder(context, AppDatabase::class.java, "database-notes")
.addMigrations(MIGRATION_1_2).build()
}
}
val MIGRATION_1_2 = object : Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("ALTER TABLE 'database-notes' ADD COLUMN image TEXT")
}
}
The database name was exactly the same in the previous version. I copied it to rule out typos.
What have I overlooked here? Thank you in advance!
because my table is named database-notes
It would appear not, due to the failure, and is probably a misunderstanding of the difference between the database name and table name(s).
A Database can have multiple tables. The database name is the name of the file itself (the container of the components such as tables, indexes, views and triggers).
In your code database-notes, as per the 3rd parameter to the Room.databaseBuilder is the name of the database (the file).
With Room the table names are derived from the classes that are both annotated with #Entity and provided, via the entities parameter of the #Database annotation. In your case the Note class.
The name of the table will be Note unless you use the tableName = parameter of the #Entity annotation to provide another name.
Example
If the following were your Note class :-
#Entity // No tableName parameter so the table name is the class name
data class Note(
#PrimaryKey
var noteId: Long? = null,
var noteText: String,
var image: String
)
Then the table name would be Note (the name of the class)
If the Note class were :-
#Entity(tableName = "notes") //<<<<< specifically names the table
data class Note(
#PrimaryKey
var noteId: Long? = null,
var noteText: String,
var image: String
)
The the table name would be notes (as specified by the tableName = parameter of the #Entity annotation).
I have changed a column type from Float to Int, how can I migrate the change so I won't lost old entries, instead just to convert all of them to the Int.
You need to add a Migration that will create the table in it's new form and copy the data from it's old form.
The SQL for the new form can be ascertained by looking at the generated java (visible from the Android View of Android Studio). Look at the class that is named the same as the class that is annotated with #Database but suffixed with _Impl, and then find the SQL in the method named createAllTables
You could then use the following
:-
DROP, just in case the intermediate old table e.g. DROP TABLE IF EXISTS table_old;
RENAME the original table using SQL based upon ALTER TABLE the_table RENAME TO the_table_old;
Create the new table using the SQL as obtained above
Copy the data using SQL based upon INSERT INTO the_table SELECT * FROM the_table_old;
DROP the now defunct old table e.g. DROP TABLE IF EXISTS table_old;;
Demo
As an example where the entity is (was commented out) :-
#Entity(tableName = "jourTable")
class Note(
#ColumnInfo(name = "title") val jourTitle:String,
#ColumnInfo(name = "description") val jourDescription:String,
#ColumnInfo(name = "date") val jourDate:String,
#ColumnInfo(name = "image", typeAffinity = ColumnInfo.BLOB) val jourImage: Bitmap?, //<<<<< will use the TypeConverter
//#ColumnInfo(name = "altImage") val jourAltImage: ByteArray //<<<<< will not use the TypeConverter
#ColumnInfo(name = "altImage") val jourAltImage: Int
) {
#PrimaryKey(autoGenerate = true)var id=0
}
i.e. commented out jourAltImage was ByteArray now to be Int (INTEGER type in SQL)
and the generated java is obtained via :-
The the #Database annotated class (TheDatabase) has :-
#TypeConverters(ImageConverter::class)
#Database(entities = [Note::class], version = 2 /*<<<<<<<<<< INCREASE FROM 1 to 2 (or as required)*/, exportSchema = false)
abstract class TheDatabase: RoomDatabase() {
abstract fun getAllDao(): AllDao
companion object {
#Volatile
private var instance: TheDatabase ? = null
fun getInstance(context: Context): TheDatabase {
if (instance == null) {
instance = Room.databaseBuilder(context,TheDatabase::class.java,"the_database.db")
.allowMainThreadQueries()
.addMigrations(MIG_1_2) //<<<<<<<<<< ADD the migration
.build()
}
return instance as TheDatabase
}
/*<<<<<<<<<< The Migration >>>>>>>>>> */
val MIG_1_2 = object: Migration(1,2){
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("DROP TABLE IF EXISTS jourTable_old;")
db.execSQL("ALTER TABLE jourTable RENAME TO jourTable_old ")
/* SQL ON NEXT LINE COPIED FROM GENERATED JAVA */
db.execSQL("CREATE TABLE IF NOT EXISTS `jourTable` (`title` TEXT NOT NULL, `description` TEXT NOT NULL, `date` TEXT NOT NULL, `image` BLOB, `altImage` INTEGER NOT NULL, `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL)")
db.execSQL("INSERT INTO jourTable SELECT * FROM jourTable_old")
db.execSQL("DROP TABLE IF EXISTS jourTable_old")
}
}
}
}
The when run App Inspection shows (it had 1 row) and the app adds 1 new row when run :-
as cab seen the altimage column is now INTEGER (was BLOB) and the 1 row has been retained.
I'm new to android room library. I need to migrate a Not Null column to Null,
But room migration only allow ADD or RENAME in ALTER table query. How do execute a column migration query?
#Entity(tableName = "vehicle_detail")
data class VehicleDetailsEntity(
#PrimaryKey(autoGenerate = true)
val vehicleClientId: Long = 0,
val vehicleId: String,
val updatedOn: Date,
val updatedBy: String
)
I need to change table structure into
#Entity(tableName = "vehicle_detail")
data class VehicleDetailsEntity(
#PrimaryKey(autoGenerate = true)
val vehicleClientId: Long = 0,
val vehicleId: String,
val updatedOn: Date?,
val updatedBy: String?
)
java.lang.IllegalStateException: Room cannot verify the data integrity. Looks like you've changed schema but forgot to update the version number. You can simply fix this by increasing the version number.
You need to run a migration since SQLite doesn't allow column constraint modification.
For that migration you need to create a new temp table and copy all your previous data to it, then delete the old table and rename the temp one to the needed table name.
If you have a scheme directory, you can find your exact creation SQL query which you should copy on your migration (I just figured it out from a scheme of mine and could not be 100% correct):
val MIGRATION_1_2: Migration = object : Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
// Create the new table
database.execSQL(
"CREATE TABLE IF NOT EXISTS VehicleDetailsEntityTmp (vehicleId TEXT NOT NULL, updatedOn TEXT, updatedBy TEXT,vehicleClientId INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL )"
)
// Copy the data
database.execSQL(
"INSERT INTO VehicleDetailsEntityTmp (vehicleId, updatedOn, updatedBy ,vehicleClientId) SELECT vehicleId, updatedOn, updatedBy ,vehicleClientId FROM VehicleDetailsEntity ")
// Remove the old table
database.execSQL("DROP TABLE VehicleDetailsEntity")
// Change the table name to the correct one
database.execSQL("ALTER TABLE VehicleDetailsEntityTmp RENAME TO VehicleDetailsEntity")
}
}