How to create an sqlite view to be used with Room? - android

I am trying to migrate my database over to use Android's Room Architecture. However I have some complex sqlite View's in my application. I don't see any information or documentation on how to create a view with room. Can anyone give me examples or point to tutorials?

You can use androidx.room.DatabaseView annotation
Example from documentation:
#DatabaseView("SELECT id, last_name FROM User")
public class UserSummary {
public long id;
#ColumnInfo(name = "last_name")
public String lastName;
}

A view in sql is just a live updating query. Using LiveData you can get the live updates, and you can simply create a new entity to use specifically for your view. This class will hold all the data your view will. Then in your entities DAO you paste your sql query associated with the view.

As of now, there is an open issue in Android Room to support Database Views in the state of Fixed, perhaps waiting for creators to support it would be a good call.
although using a hacky method you might get it done:
You may create an #Entity similar to your view (in columns) then onCreate of the database drop the table generated for this Entity.
Room
.databaseBuilder(context, DueDatabase.class, DB_NAME)
.addCallback(new RoomDatabase.Callback() {
#Override
public void onCreate(#NonNull SupportSQLiteDatabase db) {
super.onCreate(db);
//Drop the fake table and create a view with the same name
db.execSQL("DROP TABLE view_name");
db.execSQL("CREATE VIEW view_name " +
"AS SELECT [...]"
);
}
})
.build();
this way room would let you use the view name in queries and map the retrieved data on your #Entity class correctly,
although you have to keep in mind that this approach will break the migration.
for migrations to work you have to find a workaround (maybe drop your view and recreate the fake table might work)

Related

Android Room persistance library. Drop Table

I need to know how to "DROP FROM Table" using Room Persistence Library.
I already know that we can delete all the rows using the method:
#Query("DELETE FROM table")
void deleteAll();
However, what I need is deleting the whole table. This is because of my primary_key is an autoincrement column, so using the previous code, it is not rested.
I already read answers about this topic in the next links:
Reset auto-increment in Android's Room library
Android Room - reset auto generated key on each app run
However, I can't believe that this library doesn't provide an easier way to do this, regardless of the reason or use.
Could use Migrations that Room provides for updating the database via our own queries. As we want to make changes to the database which Room cannot resolve (yet) from the code. We could delete the table, recreate it or update it. Depending on what is needed.
Option 1: Migrate with keeping other data
First increase the version of the database: update the version parameter in the #Database annotation.
Create a migration like this:
static final Migration MIGRATION_1_2 = new Migration(1, 2) { // From version 1 to version 2
#Override
public void migrate(SupportSQLiteDatabase database) {
// Remove the table
database.execSQL("DROP TABLE my_table"); // Use the right table name
// OR: We could update it, by using an ALTER query
// OR: If needed, we can create the table again with the required settings
// database.execSQL("CREATE TABLE IF NOT EXISTS my_table (id INTEGER, PRIMARY KEY(id), ...)")
}
};
Add the migration when building the database:
Room.databaseBuilder(context, MyDatabase.class, "mydatabase")
.addMigration(MIGRATION_1_2) // Add the migration
.build();
Run the app again. If the queries were correct, the migration is done
Option 2: Migrate with losing data
There is also a fast option, but all data in the database will be cleared!
This is because the database gets recreated when using the method below.
Like option one, increment the version of the database
Use .fallbackToDestructiveMigration() when creating the database, like so:
Room.databaseBuilder(context, MyDatabase.class, "mydatabase")
.fallbackToDestructiveMigration()
.build();
Run the app. It will remove the old database and recreate it. (All earlier data is wiped)
If you want to do this with auto migration then need to use spec as autoMigrations value for #Database annotation. Look like
this
autoMigrations = {#AutoMigration(from = 1, to = 2, spec = AppDatabase.MyAutoMigration.class)}
Example like you want to delete a table(YourTableName) from database version 1 and then migrate to version 2 then the full code looks like this
#Database(
version = 2,
entities = {Entity1.class, Entity2.class},
autoMigrations = {#AutoMigration(from = 1, to = 2, spec = AppDatabase.MyAutoMigration.class)},
exportSchema = true)
#TypeConverters({Converters.class})
public abstract class AppDatabase extends RoomDatabase {
#DeleteTable.Entries(value = #DeleteTable(tableName = "YourTableName"))
public static class MyAutoMigration implements AutoMigrationSpec {
}
// Your DAO 1
// Your DAO 2
}

Room with Multi user Database in Single android App

Can we have a multiple databases in single android App using Room? I want to create a new database for every single user. If user1 logged in I have to create a Database for that user like UserDB1, If any new account added I have to create a another Database for that user like UserDb2. If account switch happened between that accounts I should access the user specific Database.How can i achieve that?
I did that like below,
private static AppDatabase buildDatabase(final Context appContext, int userId) {
return Room.databaseBuilder(appContext, AppDatabase.class, DATABASE_NAME + "_" + userId)
.addCallback(new Callback() {
#Override
public void onCreate(#NonNull SupportSQLiteDatabase db) {
super.onCreate(db);
}
})
.build();
}
I understand your requirement totally. There are 3 ways,
(Let's say only need a table userTable, but actually we have more.)
Create a database for each login user. (You asked, I also used it)
Only a database, but create a table for each user, such as userTable_1. (It seems that Room can't support it )
Only a database and a table for all users, so we have to add a extra column user_id to the table; if we have 20 table, we have to add "user_id" to all 20 tables. (We did it in the backend development at the most time; but in the case, I really do NOT prefer to this one)
Maybe you could but this approach is wrong for several reasons. You dont make separate databases for users you make tables with relations to each other, each row is an entry for a user.
Some tables have a one-to-many relationship like a table that holds order numbers. One user may have many orders. Or the table may have a one-to-one relationship like a user profile. What it breaks down to is, each user has a unique entry and ID, that ID would relate to other tables with their data. You use the ID for the logged in person to get their data.
Beyond that, you really shouldnt be storing other peoples data in your app, what is the situation where you feel multiple people will be using the same phone for the app? The ideal situation is to have a cloud based server/database that you get your data from so only the current users data is retrieved.
The final reason you dont do multiple databases is that if you want to add a new field you would have to update every DB created instead of just one.

Adding column in room db

I have been going through Room DB introduced in new architecture components in Android and thinking about migrating my current DBs to Room DBs.
But my current db implementation allows me to add columns to the table but as per Room, fields in POJO class represents the columns of table.
It is possible to add columns in Room DB using raw query, if yes, how shall I implement it.
I know this is an old post, but this might help someone out there that needs help with this.
Do you want to add said column on an upgrade of a DB or would you like to do it on first creation of the table?
If you want to do it on an upgrade of the DB then you can look at
Migrating Room databases
Room.databaseBuilder(getApplicationContext(), MyDb.class, "database-name")
.addMigrations(MIGRATION_1_2, MIGRATION_2_3).build();
static final Migration MIGRATION_1_2 = new Migration(1, 2) {
#Override
public void migrate(SupportSQLiteDatabase database) {
database.execSQL("CREATE TABLE `Fruit` (`id` INTEGER, `name` TEXT, PRIMARY KEY(`id`))");
}
};
static final Migration MIGRATION_2_3 = new Migration(2, 3) {
#Override
public void migrate(SupportSQLiteDatabase database) {
database.execSQL("ALTER TABLE Book ADD COLUMN pub_year INTEGER");
}
};
If you want to add the column on the fly you will have to get the instance of your DB then can try call the following:
getDatabaseInstance().query()
There is little point for using Room with this table. After all, you cannot dynamically modify any entities or DAO methods, and so Room will not know anything about these changed columns.
If the rest of your database is Room-friendly, and you just have this one weird table, you can call getOpenHelper() on your RoomDatabase to get the SupportSQLiteOpenHelper, then work from there. The SupportSQLite... classes resemble the native Android SQLite API.

How do I completely recreate my database in Android Room?

I have a situation where I want to be able to do a hard reset of my database using Android Room. Using SQLiteOpenHelper, I could do this by writing a method to drop all tables and indices, then manually call SQLiteOpenHelper.onCreate().
I'm aware that I can get access to a SupportSQLiteOpenHelper via room and drop all the tables myself, but there doesn't seem to be a good way to kick-off the recreation process.
Also, I'm aware that I could delete every item from each table without dropping it, but that's not what I want. That doesn't reset the auto-incrementing primary key, so the "id" field of new items won't reset back to 1.
Thanks!
EDIT:
This is something I want to be able to do arbitrarily at runtime.
EDIT 2:
The method should be maintainable, i.e. not involve hand-writing SQL that matches Room's behavior. Ideally there would be some way to retrieve the SQL that Room generates, or a SQLiteOpenHelper.onCreate() equivalent method. Or anything else that solves this problem! :)
I found it easiest to do this via context.deleteDatabase(“name”) and then simply reinstantiating and repopulating the database via the Room.databaseBuilder().addCallback upon first access.
Simple answer is to increment your #Database version number. Generally speaking you should do this for schema changes, however it will achieve your aims of clearing the database and resetting all primary key values.
#Database(entities = { Hello.class }}, version = 1) // <- you want to increase version by 1
#TypeConverters({})
public abstract class AppDatabase extends RoomDatabase {
public abstract HelloDao helloTextDao();
}
EDIT: IF you want to do this at run time, I would clear all the data from your tables (to avoid FK issues), then call DROP TABLE table_name, on all of your respective tables. Then you will need to write queries for creating the tables ie : CREATE TABLE table_name (uid INTEGER PRIMARY KEY, name STRING);.
This will mean you have to maintain a list of create table queries up to date with your POJO's unfortunatly. Ideally you'd be able to use reflection to generate the query, howerever #ColumnInfo currently doesn't support reflection as it has its RetentionPolicy set to CLASS.
Hopefully this solves your problem, feel free to ask for further clarification in the comments. Happy hunting!
For my case, deleting database with context.deleteDatabase(“name”) still caches the data of the old database.
I solved this by manually deleting the database file
File databasesDir = new File(context.getApplicationInfo().dataDir + "/databases");
new File(databasesDir, "MyDatabaseName.db").delete();
I was not able to find a way to do this programatically.
But, you can go to yourApp -> Long click -> App Info -> Storage & Cache -> clear both cache and Storage.
Clearing storage displays a verification dialog that indicates that databases will be destroyed.
This may help you.
upgrade your Database version
When you call DatabaseBuilder, remember add this to your code fallbackToDestructiveMigration
Room.databaseBuilder(context, Database::class.java, DB_NAME)
.allowMainThreadQueries()
.fallbackToDestructiveMigration()
.build()
More detail please refer this
As per the answers given here, and here, and here, I could do it as following:
public void deleteAndReset() {
SQLiteDatabase database;
database = SQLiteDatabase.openOrCreateDatabase(context.getDatabasePath(MY_DATABASE_NAME), null);
String deleteTable = "DELETE FROM " + MY_TABLE_NAME;
database.execSQL(deleteTable);
String deleteSqliteSequence = "DELETE FROM sqlite_sequence WHERE name = '" + MY_TABLE_NAME + "'";
database.execSQL(deleteSqliteSequence);
}

How to migrate existing SQLite application to Room Persistance Library?

It might be a bit early to ask, but is it possible and how to migrate/upgrade an existing SQLite database application to a new Android Room Persistance Library?
Assuming your room entities match your current table schemas, you can keep using the same database/tables.
Room manages a master table which is initialized on creation or upgrade of the database, so you need to increment your database version and provide a dummy migration:
#Database(entities = SomeEntity.class, version = EXISTING_VERSION + 1)
public class MyDatabase extends RoomDatabase {
// ...
}
MyDatabase db = Room.databaseBuilder(context, MyDatabase.class, "db_name")
.addMigrations(new Migration(EXISTING_VERSION, EXISTING_VERSION + 1) {
#Override
public void migrate(SupportSQLiteDatabase database) {
// NOOP
}
}).build();
For those who are wondering if there is any way to migrate from SQLite to Room even if your schema does not match, the answer is YES, you can migrate from SQLite to room even if the schema does not match.
It is possible, but a requires quite careful conversions. As the process requires so many steps to cover, I will just leave references you can follow.
Incrementally migrate from SQLite to Room
Hope it will be helpful for a few.

Categories

Resources