Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
 }
like image 968
ip696 Avatar asked May 21 '15 03:05

ip696


3 Answers

        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);
        }
like image 101
Ilya Vorobiev Avatar answered Nov 15 '22 09:11

Ilya Vorobiev


Try this:

 public void logOut() {
     new Delete().from(MyClass.class).executeSingle();
 }
like image 42
jlopez Avatar answered Nov 15 '22 08:11

jlopez


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.

like image 31
Muneef M Avatar answered Nov 15 '22 08:11

Muneef M