Jordy Jordy - 1 month ago 20
Java Question

delete database android sqlite

I want to create a logout button which will drop the entire database and finishes the current activity and redirect to the LoginActivity.

This does work but I need to restart my application to commit the changes.
For example, when the app goes back to the LoginActivity it will still see the user data. If I restart the app it will show me the login form as it should be.
How can i accomplish this?

My code:

Globals.java

public void signOff(){

SharedPreferences preferences = instance.context.getSharedPreferences("globals", 0);
preferences.edit().remove("domain").commit();

DatabaseHelper dbHelper = new DatabaseHelper(instance.context);
dbHelper.deleteData();


finish();
Intent mainActivity = new Intent(instance.context, LoginActivity.class);
instance.context.startActivity(mainActivity);
}


DatabaseHelper.java

public final class DatabaseHelper extends SQLiteOpenHelper {

public SQLiteDatabase db;

public static DatabaseHelper instance ;
public static Context context;
public static final String DATABASE_NAME = "Oryx.db";
public static final int DATABASE_VERSION = 1;

public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);

// Init the singleton
if (instance == null){
instance = this;
instance.context = context;
instance.db = instance.getWritableDatabase();
}
}

public DatabaseHelper(Context context, String tableCreateQuery)
{
this(context);
instance.db.execSQL(tableCreateQuery);
}

@Override
public void onCreate(SQLiteDatabase db) {
}

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

}

public void deleteData(){
instance.context.deleteDatabase(DATABASE_NAME);
}
}

Answer

Turned out I had to close the database and set the instance to null. In combination with the answer Pratik supplied it works.

   public static void closeDatabase(){
       instance.db.close();
       instance = null;
   }

   public static void deleteDatabase(Context mContext){
       mContext.deleteDatabase(DATABASE_NAME);
   }