How can clear all tables in ActiveAndroid?
Asked Answered
G

2

7

I have about 20-30 tables in my ActiveAndroid database. When I press logoutButton I want to clear all the tables. How can I do it in ActiveAndroid?

 public void logOut() {
     //clear all tables
 }
Germaun answered 21/5, 2015 at 3:53 Comment(3)
You are asking for a complete solution. This is encouraged on Stackoverflow. Instead, write your own code and when you encounter a problem, (1) search for an answer, (2) only ask if you have not found it.Stover
I ask a specific question. how to clean the base.Germaun
Delete the database fileThracian
F
10
        SQLiteDatabase db = ActiveAndroid.getDatabase();
        List<String> tables = new ArrayList<>();
        Cursor cursor = db.rawQuery("SELECT * FROM sqlite_master WHERE type='table';", null);
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            String tableName = cursor.getString(1);
            if (!tableName.equals("android_metadata") &&
                    !tableName.equals("sqlite_sequence")) {
                tables.add(tableName);
            }
            cursor.moveToNext();
        }
        cursor.close();
        for (String tableName : tables) {
            db.execSQL("DELETE FROM " + tableName);
        }
Feria answered 21/5, 2015 at 5:7 Comment(3)
Good. I have all names of my tables. How can i clear this tables?Germaun
Sorry, forgot to add deletingFeria
I'm getting a SQLiteConstraintException because I have a foreign key between some of my tables. Any solution to handle this?Frei
C
1

Hope this could help someone using Active Android.

for deleting all the records in a table there is an easy way.

1) First Create class "TruncatableModel" and extend all your Models to this class

public abstract class TruncatableModel extends Model {
    public static void truncate(Class<? extends Model> type){
        final String tableName = Cache.getTableInfo(type).getTableName();

        // Delete all rows from table
        ActiveAndroid.execSQL(String.format("DELETE FROM %s;", tableName));

        // Reset ids
        ActiveAndroid.execSQL(String.format("DELETE FROM sqlite_sequence WHERE name='%s';", tableName));
    }
}

.. so after extending, my model class would look like.

@Table(name = "note")
public class Note extends TruncatableModel {
    @Column(name ="idn")
    public Integer idn;
    @Column(name ="title")
    public String title;
    ...
}

2) Now i can delete all the records in "note" database using this code.

Note.truncate(Note.class);

This seems to be more efficient way than any other methods i have tried.

Chrysotile answered 31/1, 2017 at 19:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.