ip696
ip696

Reputation: 7084

How can clear all tables in ActiveAndroid?

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
 }

Upvotes: 7

Views: 3786

Answers (2)

Muneef M
Muneef M

Reputation: 1114

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.

Upvotes: 1

Ilya Vorobiev
Ilya Vorobiev

Reputation: 836

        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);
        }

Upvotes: 10

Related Questions