I use Sugar ORM 1.5 in my app and I want to clear all info when the user logoff.
I want to avoid deleting the database file or use pure SQLite scripts if possible.
The only solution I found was using deleteAll on all tables, but I want to know if there is a better way to do it.
Regards,
EDIT
I solve the problem I had deleting the database just calling SugarContext.terminate(); before deleting the database and SugarContext.init(context); after.
Looks like it's the best solution like Henry Dang pointed in the comments, and it is faster than deleting all data.
This snippet works for me. It terminates the context deletes all tables and recreates them:
SugarContext.terminate();
SchemaGenerator schemaGenerator = new SchemaGenerator(getApplicationContext());
schemaGenerator.deleteTables(new SugarDb(getApplicationContext()).getDB());
SugarContext.init(getApplicationContext());
schemaGenerator.createDatabase(new SugarDb(getApplicationContext()).getDB());
SchemaGenerator is from com.orm, my SugarORM version is 1.5.
for other users who just want to delete all records (not tables or database)
public static void deleteAllrecords(Context applicationContext) {
List<Class> domainClasses = getDomainClasses(applicationContext);
for (Class domain : domainClasses) {
SugarRecord.deleteAll(domain);
}
}
if we want to delete sequence also you can add this line inside for loop
SugarRecord.executeQuery("DELETE FROM SQLITE_SEQUENCE WHERE NAME = '" + NamingHelper.toSQLName(domain) + "'");
Related
I'm trying to rename a column in my Room database. I foolishly used the column name index and want to change it to id, but this migration function is causing headaches:
static final Migration MIGRATION_2_3 = new Migration(2, 3) {
#Override
public void migrate(#NonNull SupportSQLiteDatabase database) {
database.execSQL("ALTER TABLE items RENAME COLUMN index TO id;");
}
};
I followed this syntax diagram for the query:
Android Studio is giving me the error TO expected, got 'COLUMN', and I cannot use the database due to the RuntimeException:
Caused by: 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.
The version number is correct, so I am assuming this issue is caused by the syntax problem above; I cannot find anything else wrong with my setup.
Android uses SQLite v3.19. That makes renaming a column using RENAME COLUMN not possible. The best approach is to recreate the table. – Leo Pelozo
Looks like I need to create function that drops the table so I can create a new one.
#Query("DELETE FROM items")
void dropTable();
... then create the table again, though I'm not sure how to go about this.
Update:
I was able (I think, we'll see...) to re-create the table by calling the above function, removing ALL migrations and setting the database version back to 1. Then I re-defined the database class itself with the proper names etc. and was able to insert data into it without any errors. Adding .fallbackToDestructiveMigration() to my database singleton class was also necessary.
Personally I think this is a little ridiculous just for simply re-naming a column; I was never able to simply rename the column and add a migration for the change, nor was I able to drop the table and re-create it with the proper column name and add that as a migration. But alas, this is Android after all.
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);
}
I have around 2600 entries in my SQLite database. I need to delete all those entries and put in updated entries. I know that the database can be updated by changing the database version in the DatabaseHandler class, but that can only be done if the whole app is updated. I need to programatically update the database. Can this be done? I searched but couldn't find a satisfactory answer. Thanks.
I guess you can call a method some what like this
public void emptyDatabase() {
db = this.getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_Your_Tbl);
}
Even this will be able to delete those values quickly. Without updating the version number.
Plus as you mentioned that you have to delete the records and add new values.
It will be much faster that updating those values.
In my application, I want to delete my existing database and create a new one with default values. Default values can be inserted to the database from XML.
Does anyone have any idea on how to reuse a database?
Assuming that you are using a SQLite database, to delete all the rows from all of your tables inside your database you can use db.execSQL() and heed the advice from this question Drop all tables command:
You can do it with the following DANGEROUS commands:
PRAGMA writable_schema = 1;
delete from sqlite_master where type = 'table';
PRAGMA writable_schema = 0;
you then want to recover the deleted space with
VACUUM
and a good test to make sure everything is ok
PRAGMA INTEGRITY_CHECK;
If you haven't written a way to read your XML data yet, this is excellent reading: Store parsed xml data to sqlite ? Android
Well basically that's not an Android specific question.
Firstly when do you want to recreate the database with default values and how to trigget it.
In an UI event like button click etc?
Or when you start/stop or destroy your activity?
In any cases you need to drop the database and recreate the whole structure (tables,relationships etc.) again.
How do i delete a whole table in android through code?
I'd say just use a DROP TABLE query?
(I'm asuming you're talking about a database, and you're using the SQLite that's in Android, right? http://www.sqlite.org/lang_droptable.html )
an example as requested:
DROP TABLE IF EXISTS mydatabase.myTable
You can delete a database easily by writing a test case inheriting from AndroidTestCase (You don't have to but its an option), that way you will get access to Context, and call deleteDatabase("mydatabase.db") on it.