How to delete not only tables but a database in Sqlite

Asked

Viewed 1,783 times

0

I would like to delete not only a table but the database as a whole in Sqlite. Searching, I was told of a method Context.deleteDatabase(), but I can’t use, if I try to call in a method, it says it’s not static to be used in a static class, and I don’t know how to instantiate a "context" object to use that function.

This is my Helper class:

public class bdHelperUser extends SQLiteOpenHelper {
    private static final String NOME_BD = "user.db";
    private static final int VERSAO_BD = 1;

    public bdHelperUser(Context ctx){
        super(ctx, NOME_BD, null, VERSAO_BD);//o terceiro item é um cursor factor (não obrigatório)
    }

    @Override
    public void onCreate(SQLiteDatabase sqlite) {
        //tabela principal de dados dos usuários
        String sql = "create table if not exists usuario (_id integer primary key autoincrement, " +
                "nome text not null, endereco text not null, senha text not null, " +
                "mail text not null, cpf text not null, telefone text not null, " +
                "sexo text not null, dt_nascimento text not null, auto_login integer, " +
                "pin number(4), foto blob, apelido text);";

        sqlite.execSQL(sql);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        //a cada versão nova do banco o script de mudança deve ser inserido


    }
}

This is the method I want to delete everything to the bank:

public void deletarConta(View v) {

        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        builder.setTitle(getString(R.string.deletar_conta_titulo));

        builder.setIcon(R.drawable.del);

        builder.setMessage(getString(R.string.deletar_conta_confima));

        builder.setPositiveButton(R.string.confirma, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface arg0, int arg1) {
               String resposta =  crud.deletarUsuario(,"user.db");//aqui ocorre o erro
               exibirMsg(resposta);
                finish();
                login();
            }
        });

        builder.setNegativeButton(R.string.cancela, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface arg0, int arg1) {

            }
        });

        alerta = builder.create();

        alerta.show();
    }

And this is the method that deletes data in the database:

public String deletarUsuario(Context ctx, String strg){

        try {
            sqLite = helper.getWritableDatabase();
            sqLite.delete("usuario", null, null);
            //sqLite.deleteDatabase(file);
            //sqLite.execSQL("DROP TABLE IF EXISTS visitas");
            sqLite.close();
            ctx.deleteDatabase(strg);//aqui não consigo chamar esse método na activity pois não sei como criar um objeto Context pra passar como parâmetro e nem posso chamar esse método diretamente na classe

            return "Deletado com sucesso";
        }catch (SQLException erro){
           erro.getMessage();
            return "erro ao deletar";
        }
    }

Can anyone help me by launching an example of how to do this via API, I know that if I delete the APP and reinstall it works but wanted to know how to program.

  • To delete the database, you also need to pass the database extension. Example: ctx.deleteDatabase("databasename.db");

  • this "ctx".deleteDatabase... is a right context? How do I create the instance of this context to use the Contexte class method (deleteDatabase)???

  • When you use the method deletarUsuario, you obviously depending on the activity that you are, it should be something like deletarUsuario(this, "databasename.db")

  • I tried using getBaseContext but it didn’t work, I’ll try as you say. Thank you!

  • If you’re doing it in a fragment, then you instead of using this, puts getActivity(). Thus: deletarUsuario(getActivity(), "databasename.db")

  • It’s not a Fragment but it was good to know, so test warning here if it worked out thank you!

  • @Adsonlucassilvadefarias The answer solved your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).

Show 2 more comments

1 answer

1

I believe this should serve:

sqlite.deleteDatabase("nome do banco");

Or this:

ctx.deleteDatabase("nome do banco");
  • I believe ctx.deleteDatabase("bank name"); solve my problem but I don’t know how to call this method in the class. Do you have any example of how to use? How I caught an instance of Context in android studio?

  • It depends on how you want to use it. Classes should be built according to need. You need to see how and why you want to erase the entire database and provide the necessary resource to be consumed as needed.

  • I am building an app to serve as a study base in mobile programming (android), I created one of it to delete the user account, and when I delete only the table I am unable to create a user again unless I delete the entire app and later install again, in the midst of some tests I did found out that if I change the name of the bank I can create a new user without having to delete the app, then I came to the idea that I had to delete the entire bank so the table to be able to recreate and register a new user.

  • I may be mistaken, but for me this is gambiarra, I think better to look for a better solution for the architecture.

  • Hummm, I don’t know if it’s a system bug but I delete the user table and when I try to register a new user I can’t get my Helper class apparently ok. But thanks for the tip!

  • Yes, it’s possible it’s a bug of your system.

Show 1 more comment

Browser other questions tagged

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