My main activity does some initial things and than starts InitDBActivity. This one is supposed to check i database is up to date and update it if necessary. The following is done in InitDBActivity’s onCreate method.
Thread asyncDBCreation = new Thread(new Runnable() {
public void run() {
SQLiteDatabase db = null;
try{
db = dbh.getWritableDatabase();
}catch(Exception ex){
return;
}
if(dbh.recreateDB(db)){
try{
dbh.insertQueries(dbh.getQueries(getAssets()),db);
}catch(Exception ex){
dbh.close();
finish();
return;
}
dbh.close();
prefEdit.putLong(dbVersion, dbFileVersion);
prefEdit.commit();
startActivity(intent);
finish();
}
else{
}
}
});
asyncDBCreation.start();
The problem is that if the user clicks the ‘back’ button he exits the app, but this thread is still running in background. It wold be fine – the job gets gone anyway, but… it turns out that if he launches the application again before this thread finishes – everything messes up. Data in database is multiplied. How can I kill this thread?
in java, dont have method can kill thread, only interrupt the thread, you can use method:
thread.interrupt()to interrupt thread, but the thread must in the state which can be interrupted, like: sleep, or wait.so, here you can use
db.closemethod to close database, the data query work will throw exception, you can catch the exception to finish the thread work.