问题描述:

I use an insert query in onCreate and I want to delete all that data in onDestroy but I cant make it work, everytime I start the application the data is doubled. It seems that onDestroy is not working.

checkout my codes

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_student_view);

toolbar = (Toolbar) findViewById(R.id.toolbar);

setSupportActionBar(toolbar);

myDbHelper = new DatabaseHelper(this, DATABASE_NAME, null,

DATABASE_VERSION);

sqlHandler = new SQLHandler(this);

mDb = myDbHelper.getWritableDatabase();

String query = "INSERT INTO scholar_table(Name,Top,Continent,Region,Location,Introduction,Alumni) " +

"values ('Wesleyan University Philippines','290','Luzon','Region 3','Nueva Ecija','WUP Intro','WUP Alumni')";

sqlHandler.executeQuery(query);

}

@Override

public void onDestroy(){

super.onDestroy();

sqlHandler = new SQLHandler(this);

mDb = myDbHelper.getWritableDatabase();

String query = "DELETE * FROM scholar_table";

sqlHandler.executeQuery(query);

finish();

}

网友答案:

I recommend putting your SQLite into another file.

Take this file: https://github.com/kweaver00/Android-Samples/blob/master/Storage/SQLite/LocalStorageApp/app/src/main/java/com/weaverprojects/localstorageapp/Controller/LocalDB.java

And make your onCreate():

Log.v(TAG, "Number of rows:" + String.valueOf(mLocalDB.numberOfRows()));
mLocalDB = new LocalDB(this, "db", null, 1);
mLocalDB.insert("John", "Smith");
Log.v(TAG, "Number of rows:" + String.valueOf(mLocalDB.numberOfRows()));

and in your onDestroy:

Log.v(TAG, "Number of rows:" + String.valueOf(mLocalDB.numberOfRows()));
mLocalDB.deleteRow(1);
Log.v(TAG, "Number of rows:" + String.valueOf(mLocalDB.numberOfRows()));

Probably change the parameters of deleteRow to meet your needs, or delete every row:

for(int i = 0;i<mLocalDB.numberOfRows();i++){
    mLocalDB.deleteRow(i);
}

or "i" may start at 1 instead.

网友答案:

Try placing the essential code to onStop() method, might help you solve the problem

Basically, there's never a guarantee that onDestroy() will be called, and in some cases processes such as your app will be killed directly, bypassing the method call anyway.

Take a look at this: Activity OnDestroy never called?

And this:

http://developer.android.com/reference/android/app/Activity.html#onDestroy%28%29

相关阅读:
Top