Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically erase data of a sqlite database using ormlite library

I'd looking for a method to erase all data of a ormlite database or delete the database (and then recreate it) with ormlite on android.

At this time, I can only change the DATABASE_VERSION of the DatabaseHelper.

But I have to compile the application.

Does someone know a method to handle that case?

like image 415
P. Sohm Avatar asked Feb 16 '12 09:02

P. Sohm


People also ask

How do I delete multiple records in SQLite?

If you wanted to delete a number of rows within a range, you can use the AND operator with the BETWEEN operator. DELETE FROM table_name WHERE column_name BETWEEN value 1 AND value 2; Another way to delete multiple rows is to use the IN operator.

How to delete data in Android Studio?

3.1 Add the Clear all data menu optionIn the Options menu, select Clear all data. All words should disappear. Restart the app. (Restart it from your device or the emulator; don't run it again from Android Studio) You should see the initial set of words.


3 Answers

I'd looking for a method to erase all data of a ormlite database or delete the database (and then recreate it) with ormlite on android.

@Julia's answer will work well. ORMLite also supports a TableUtils.clearTable() method call which removes all rows from a table:

That won't clear a database but you can clear each table in turn. Something like the following:

TableUtils.clearTable(getConnectionSource(), YourClassHere.class);

Edit:

@max4ever pointed out that context.deleteDatabase(...) is a lot faster than other ways of clearing a database. But this call will remove the table definitions while TableUtils.clearTable(...) leaves the schema intact.

like image 95
Gray Avatar answered Oct 19 '22 10:10

Gray


You can call

context.deleteDatabase(DATABASE_NAME);

in your DatabaseHelper class which extends OrmLiteSqliteOpenHelper. context is passed to the DatabaseHelper class in the constructor.

The next time the database is needed, it is recreated and

@Override
public void onCreate(SQLiteDatabase sqliteDatabase, ConnectionSource connectionSource)

is called.

like image 25
Julia Avatar answered Oct 19 '22 09:10

Julia


To delete the database use these commands:

this.connectionSource.close();
context.deleteDatabase(DATABASE_NAME);

To recreate/open the current database use these commands:

SQLiteDatabase db = context.openOrCreateDatabase(DATABASE_NAME, 0, null);
this.connectionSource = new AndroidConnectionSource(db);

You will have to keep a reference to the context in your database helper.

like image 3
superdave Avatar answered Oct 19 '22 10:10

superdave