Search code examples
androiddatabasesqliteandroid-studioandroid-sqlite

How to delete all SQLite data from android studio?


I'm trying to delete all data from an SQLite database when a user presses a button. But the app keeps crashing when I press the remove button. I tried using the delete method. But the result is same

Here is my reset method on DatabaseHelper:

public void onCreate(SQLiteDatabase sqLiteDatabase) {
   
    sqLiteDatabase.execSQL("Create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,MAIL TEXT,PASS TEXT);");
}
public void reset () {
    SQLiteDatabase db=this.getWritableDatabase();
    db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
    onCreate(db);
}

On Main Activity:

clearData.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            alart=new AlertDialog.Builder(Home.this);
            alart.setTitle("Are you sure?");
            alart.setMessage("Are you sure want to clear all your data?");
            alart.setPositiveButton("YES", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                    mydb.reset();  // mydb is a DatabaseHelper obj

                    Toast.makeText(getApplicationContext(),"Removed",Toast.LENGTH_SHORT).show();
                }
            });
            alart.setNegativeButton("NO", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
            AlertDialog a = alart.create();
            a.show();
        }
    });

Error Message sshot Thanks in advance.


Solution

  • This might work.

    db.delete("TABLE_NAME", null, null);