I want my SQLite database instance to be wiped away when the program starts.
What I tried was make a method on my class MyDBAdapter.java like this:
p
Beside onCreate()
and onUpgrade()
you can override onOpen()
. Drop all tables there and call onCreate()
.
public class MyApplication extends Application {
protected static final String LOG_TAG = "MyApplication";
private static DatabaseAdapter mDb;
private static MyApplication mInstance;
/**
* @return The instance of the database adapter.
*/
public static DatabaseAdapter getDatabaseAdapter() {
return mDb;
}
/**
* @return The instance of the application.
*/
public static Context getInstance() {
return mInstance;
}
@Override
public void onCreate() {
super.onCreate();
Log.w(LOG_TAG, "Application::onCreate");
mInstance = this;
mDb = new DatabaseAdapter();
}
@Override
public void onTerminate() {
// Close the internal db
getDatabaseAdapter().close(DatabaseAdapter.INTERNAL);
Log.e(LOG_TAG, "::onTerminate::");
super.onTerminate();
}
}
The advantage of subclassing Application is that this will be called always when your application is started or terminated. Independent of the activity that is started. Global operations like open/close a database should be placed here.
Documentation:
Base class for those who need to maintain global application state. You can provide your own implementation by specifying its name in your AndroidManifest.xml's tag, which will cause that class to be instantiated for you when the process for your application/package is created.
There is a method you can use to tell SQLiteDatabase to delete one of the databases programatically like this:
context.deleteDatabase(DATABASE_NAME);
You need the Context and the name of your database to delete.
You could stick this in your constructor that makes the connection to the SQLite Database.
More info: how to drop database in sqlite?
Use the in-memory flag, so there is no need to clear it.
The quick and easy solution that I used was to delete the database file in the OnCreate()
method by calling another method named doDBCheck()
. The doDBCheck()
looks for the file on the emulator/phone's file system and if it exists, remove it.
private static final String DB_PATH = "data/data/<package name here>/databases/<db name>";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mainView = (TextView) findViewById(R.id.mainView);
doDBCheck();
}
private void doDBCheck()
{
try{
File file = new File(DB_PATH);
file.delete();
}catch(Exception ex)
{}
}