How to delete data from database in android studio?

Asked

Viewed 2,965 times

2

I have an application where when the user logs in the first time, I save the Token and NIU, then the next time he accesses the application, he already enters directly into the Webview using that token e NIU that are in the database. However I need to delete this data when the user click on the "Quit" button on webview. I already have a treatment for this button (exit), I can enter the treatment of erasing the database data here too, how to do?

METHOD BT_SAIR:

     private void SairWV(){
     Intent intent = new Intent(Webview.this, MainActivity.class);
     startActivity(intent);
     finish();

METHOD TO INSERT INTO THE BANK:

    public long insere (Token token){
    dao = new BancoDeDados(context);
    SQLiteDatabase db = dao.getWritableDatabase(); 
    dao.onCreate(db);
    ContentValues dados = pegaDadosDoAcesso(token); 
    long inserir = db.insert(NOMETABELA, null, dados);
    db.close();
    Log.i(NOMETABELA, inserir + "");
    return inserir;
}

3 answers

2


To delete in your database Oce follows +- the same idea that Oce is already using:

db.delete(TABELA, CHAVE + "=" + chave, null)

Where TABELA is the table you want to perform Delete, CHAVE is the identifier you use for that line you want to delete (be a primary key, the name, a date, whatever you want) and chave is the value to be compared to delete.

This returns the number of lines that have been deleted, so Voce can always test if they are > 0 to see if you really deleted.

Worth checking out on documentation:

2

To delete all data use:

db.execSQL("DELETE FROM " + NOMETABELA);

To delete only one row from the table:

db.delete(NOMETABELA, "NOMECAMPO" + "='" + VALOR + "'", null);

0

Follow an example:

   private void SairWV(){

        dao = new BancoDeDados(context);
        SQLiteDatabase db = dao.getWritableDatabase();
        /** irá remover todos os registros **/
         db.execSQL(String.format("DELETE FROM %s", NOMETABELA));
        /**
         * Quando se usa DELETE TABLE
         para excluir todos os registros,
         recomenda-se usar o comando VACUUM para
         limpar o espaço não utilizado.
         **/
        db.execSQL("VACUUM");
        Intent intent = new Intent(Webview.this, MainActivity.class);
        startActivity(intent);
        finish();
    }

source

Browser other questions tagged

You are not signed in. Login or sign up in order to post.