ORMLite reset all tables - android

I have an application that uses ORMLite. I need to create a function to reset the entire db (basically I need to delete all rows from every db, reset the autoincrement and reset indexes).
I probably can do this by launching a truncate on every table but does ORMLite has some specific method to do this?

ORMLite does not have a special method to reset the entire db. It does support the TableUtils.clearTable(connectionSource, dataClass)) method which removes all of the rows from the table, which would clear the index, but this will not reset the auto-increment. Also, I'm not sure what "reset indexes" implies more than clearing them. The process of resetting the auto-increment is going to be extremely database dependent so ORMLite will most likely never have native support that anyway.
I think your best bet is to drop the table using TableUtils.dropTable() and then re-create it with TableUtils.createTable() .

There is one way possible.. delete the database but this method is usually used when user log out and login with another user id etc, at login db is created and at logout db is deleted.
mContext.deleteDatabase("xxxxxx");
where "xxxxx" is the database name.

You can also use TableUtils.createTableIfNotExists(source,dataClass). Useful when testing.

Related

Clearing the Auto-Increment value after calling clearAllTables()

Android Room version 1.1.0 now provides the method clearAllTables().
Altough this method is very convenient, it does not clear the auto-increment value generated by the by autoGenerate(), as stated in the official documentation.
I would also like to clear the primary keys of all the tables in my database, without having to call individual queries for each table.
Based on this answer, I would assume that this SQL statement would work:
DELETE FROM sqlite_sequence WHERE name='table1' OR name='table2';
...chaining on as many OR clauses as needed.
However, sqlite_sequence is not a Room-managed table, so you may need to execute this SQL using a SupportSQLiteDatabase. You get one of those by calling getOpenHelper().getWritableDatabase() on your RoomDatabase.
However, I would not bother with this. IMHO, you should not be relying on any particular behavior of AUTOINCREMENT (e.g., always starting from some specific value). In that case, it's unclear what value there is in hacking SQLite to reset these values.

What's the price for referencial integrity of database tables on Android?

Well, the title says it all - does pragma foreign_keys = true to an existing database makes my database "less fast"?
Whenever data is added, removed, or changed, the database needs to check that the constraints still hold. The documentation lists some examples of how these checks look like.
In practice, it is very likely that you will need to access all the referenced tables anyway, so everything will be in the cache.
Furthermore, the biggest slowdown if a database write is the transaction overhead. So it is likely that the additional checking does not lead to a noticeable delay.
In any case, SELECT queries are not affected by foreign key constraints.
Although the accepted answer is sufficient, I want to put here one specific use case.
For anyone who has to imply foreign keys constraint to an existing database and probably needs to do some refactoring of the database, call setForeignKeyConstraintsEnabled in the onOpen method of the SQLiteOpenHelper.
From the book Android Enterprise:
The onOpen method is called only after onCreate, onUpgrade, and onDowngrade, leaving
those methods free to play fast and loose while they rebuild the schema. The occasion in
which an application must rename or recreate a table or two during an upgrade might be
one of the few times that it is truly a relief that foreign key constraints are not enforced.
Enabling foreign key constraints in the onOpen method causes them to be enforced only
after the database has been initialized.

on application update ,need to migrate from database to sharedpreference

In my current project's previous version we were using database for settings.
but for now we think that database is overhead for simple key value pairs
so we decided to use sharedpref for that.
Now the problem is how to handle to update functionality.
we are not using database so onUpgrade will not be work.
I am planing to do
ArrayList<String> databases = new ArrayList<String>(Arrays.asList(mContext.databaseList()));
if(databases.contains("dbname")){
copyDataToSharedPref();
mContext.deleteDatabase("dbname");
}
is there any simple way to handle this?
is there any simple way to handle this?
Not exactly but it isn't difficult. Just do something similar to the following...
When your main / launcher Activity starts get it to check SharedPreferences for a specific key, example - a boolean "update_complete".
If the key doesn't exist, there are two possibilities. The first is it's a clean (new) install, the second is it's an update.
If the key DOES exist then the app has already been updated and the database data has already been transferred to SharedPreferences so proceed to run the app.
If the key DOESN'T exist then check to see if the database exists. If the database DOESN'T exist then this is a new installation. In that case just setup SharedPreferences as a new installation.
If the key DOESN'T exist but the database DOES exist, transfer the data from the database into SharedPreferences, delete the database then put the "update_complete" boolean into SharedPreferences.
I think that covers it.
The Database entries will be there even after the App is updated (if user doesn't clear data). So in your situation I will:
check if there are is any database and its not empty.
if DB is there then read and create corresponding SharedPreferences.
delete the database using context.deleteDatabase(DATABASE_NAME);
I think that the Application class will be the best place to do so.
I am not sure if it is the best (or worst :P) method to do the same but I hope its useful.

How to modify a table in a database sent (or ship) in the application without deleting the other tables?

I'm working on an Android application that use a DB sent in the assets folder. Periodically, I need to update one of the tables in the database, but without deleting the contents of the others (because they had data from the user).
I have read that increasing the version of DB will upgrade the entire DB, but that means resetting every single table.
Is there any way to achieve this?
You can handle it internally, I'm not sure what triggers your need to update the table, the initial setup of the app or later in your processing. The process is sort of rudimentary.
Let's say table A has data and you want to add 'col_new' to it.
DROP TABLE Temp
ALTER TABLE A RENAME TO Temp
Drop table A
Create table A with all the columns Table A has plus the 'col_new'.
Query table Temp and insert it into the A table something like this
insert into A (name, phonenumber) select name, address from Temp
Check that your counts match for both the tables. Set col_new as you may.
It's probably not what you wanted to hear, but I hope it helps.
I've finally done what CommonsWare recommended: to separate databases. I changed my design so right now I have two different databases (one containing the application information and the other containing the user information).
With this I'm able to update application DB without deleting user information.

Creating multiple databases in Android

I am trying to create multiple database tables in android where each table will represent an account. I am struggling to get more then one table per database
Would anyone have any sample code they could show me? Or any suggestions?
Thanks
I don't know anything about your app, but the way you're designing your database schema sounds a little questionable. Does creating a table for every account (whatever an "account" might be) really make the most sense?
Regardless, creating tables in SQLite is pretty straightforward. In your SQLiteOpenHelper class, you can call db.execSQL(CREATE_TABLE_STATEMENT) to create a table, where CREATE_TABLE_STATEMENT is your SQL statement for a particular table. You can call this for every table you need created. This is typically going to be called in your SqliteOpenHelper's onCreate method when the database is initialized, but you can call it outside of the helper as well.
If you are going to use a fair amount of tables and data, including a prepopulated database in your assets folder is another way to go.
When I started to use databases on android I found this very helful.
http://developer.android.com/resources/tutorials/notepad/index.html
ps now that you mentioned that there are only 2-3 accounts, creating one table/account sounds much more reasonable than first expected.
But it really depends on what you are planning to do with the data and where your performance requirements are. One could even use one single table or as well multiple tables for each (fixed) type of transaction - if the data for transaction types have very different structure.
Creating database table in Android is pretty straghtforward:
db.execSQL(CREATE_TABLE_STATEMENT);
where db is SQLiteDatabase object and CREATE_TABLE_STATEMENT is your create table sql statement
As in your question you did not explain clearly the requirement of your app, but I can see a few cons in your approach of creating one table for each user
If there are many users created, u will have many tables in ur database
If later on you have some information, settings that would be shared across some users or all user, you will have to replicate them in every user single table.
My recommendation would be you have one table for users, and another table for transactions with one column is user_id to link back to the user table. It would be easier to expand or maintain your database later.
Hope it helps :)

Categories

Resources