Biblioteca de persistencia de sala. Borrar todo


¿Cómo puedo eliminar todas las entradas de una tabla específica usando Room Persistence Library? Necesito soltar la tabla, pero no puedo encontrar ninguna información sobre cómo hacer esto.

Solo cuando la base de datos está migrando o para cargar todas las entradas y eliminarlas:)

Author: Sirelon, 2017-05-29

5 answers

Puede crear un método DAO para hacer esto.

@Dao 
interface MyDao {
    @Query("DELETE FROM myTableName")
    public void nukeTable();
}
 230
Author: yigit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-29 19:45:17

A partir de la Sala 1.1.0 puedes usar clearAllTables () que:

Elimina todas las filas de todas las tablas que están registradas en esta base de datos como entities().

 37
Author: Dick Lucas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-15 19:39:33

Si desea eliminar una entrada de la tabla en la sala, simplemente llame a esta función,

@Dao
public interface myDao{
    @Delete
    void delete(MyModel model);
}

Actualización: Y si desea eliminar la tabla completa, llame a la siguiente función,

  @Query("DELETE FROM MyModel")
  void delete();

Nota: Aquí MyModel es un Nombre de Tabla.

 9
Author: Aman Gupta - ShOoTeR,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-27 09:57:47

Combinando lo que dice Dick Lucas y agregando un reinicio autoincremental de otros posts de StackOverFlow, creo que esto puede funcionar:

    fun clearAndResetAllTables(): Boolean {
        val db = db ?: return false

        // reset all auto-incrementalValues
        val query = SimpleSQLiteQuery("DELETE FROM sqlite_sequence")

        db.beginTransaction()
        return try {
            db.clearAllTables()
            db.query(query)
            db.setTransactionSuccessful()
            true
        } catch (e: Exception){
            false
        } finally {
            db.endTransaction()
        }
    }
 1
Author: Hamlet Leon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-23 10:46:08

Use clearAllTables () con RxJava como a continuación para evitar java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time.

Completable.fromAction(new Action() {
        @Override
        public void run() throws Exception {
            getRoomDatabase().clearAllTables();
        }
    }).subscribeOn(getSchedulerProvider().io())
            .observeOn(getSchedulerProvider().ui())
            .subscribe(new Action() {
                @Override
                public void run() throws Exception {
                    Log.d(TAG, "--- clearAllTables(): run() ---");
                    getInteractor().setUserAsLoggedOut();
                    getMvpView().openLoginActivity();
                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(Throwable throwable) throws Exception {
                    Log.d(TAG, "--- clearAllTables(): accept(Throwable throwable) ----");
                    Log.d(TAG, "throwable.getMessage(): "+throwable.getMessage());


                }
            });
 0
Author: whaleswallace,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-10-02 08:53:21