简体   繁体   中英

How to remove DB in method onUpgrade?

How can i remove file with my database on SQLite in method onUpgrade?

I tried:

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    context.deleteDatabase(DATABASE_NAME);

    onCreate(db);
}

error: context cannot be resolved.

and second:

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    File dbFile = getDatabasePath("your_db_file_name");
    boolean deleted = dbFile.delete();

    onCreate(db);
}

error: The method getDatabasePath(String) is undefined for the type TestDatabase.

You cannot delete the file as it is in use at the point this method is called.

Instead, if you really want to the delete the database run

File dbFile = getDatabasePath("your_db_file_name");
if(dbFile.exists() && dbFile.delete())
{
    // Create new database if that is what you want to do.
}

Before you actually instantiate the DatabaseHelper object. Without knowing the rest of your code it is hard to give a more detailed solution.

you can create a method to clean the table and call it before you add the new values to it

public void delete_ALL_ROWS()
    {
        ourHelper = new DbHelper(ourContext);
        ourDatabase = ourHelper.getWritableDatabase();

        String deleteSQL = "DELETE FROM " + DATABASE_TABLE;

        ourDatabase.execSQL(deleteSQL);

        ourHelper.close();
    }

In your onUpgrade function you should simply run the drop table statements

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // delete our old table
    db.execSQL("DROP TABLE IF EXISTS " + tableName);

    // create our new table
    onCreate(db);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM