-1

I'm currently working in one project and I need to delete one SQLiteDatabase by using a button.

So, I called the onClick "deletar" on the button:

public void deletar (View view){
    Dados_familiaOpenHelper dados_familiaOpenHelper = new Dados_familiaOpenHelper(null);
    dados_familiaOpenHelper.delete();
}

This is one the activity "secundario", where my button is from.

So, I have this class:

public class Dados_familiaOpenHelper extends SQLiteOpenHelper {

  public Dados_familiaOpenHelper(Context context){
    super(context, "Dados_familia", null, 6);
  }

  @Override
  public void onCreate(SQLiteDatabase db) {
    db.execSQL(ScriptDLL.getCreateTableCliente() );
  }

  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}

  public void delete (){
    SQLiteDatabase db = getWritableDatabase();
    db.execSQL("DELETE FROM CLIENTE");
    db.close();
  }
}

And, as you see, at the end of the class I have the method "delete", which is called by the method "deletar" in another class.

The problem is that when I run my app and press the button the app crushes, and closes. One of the possible problem is that in the method "deletar" I'm using:

Dados_familiaOpenHelper(null);

And the "Null" context could be causing me problems. It's that? What should I put between the "()"? Is there any other problem?

Just to tell you, I'm not a native English speaker and actually my English is really poor, hope you can understand it.

Ulivai
  • 121
  • 4
  • You need to pass an instance of the context, which is the hosting Activity or Service. If you don't have access to it in the class you have the error on, most likely your architecture is faulty and you are going to need a lot of refactoring. Just, please, don't use static activities instances as you are likely to come back because of more problems. – Chisko Apr 01 '18 at 02:46
  • Context is essential in Android development, passing null will most likely cause crashes and/or unexpected behavior. Never do that again and if you need it as dependency in your classes always look for a way to inject it – Chisko Apr 01 '18 at 02:53

1 Answers1

0

Or you can also use:

public void deletar (View view){
    Dados_familiaOpenHelper dados_familiaOpenHelper = new Dados_familiaOpenHelper(view.getContext());
    ...
}
Chisko
  • 3,092
  • 6
  • 27
  • 45