开发者

Android: getting rid of your sqlite database

开发者 https://www.devze.com 2023-03-28 01:23 出处:网络
I would to erase and recreate the database for my app each time I send a开发者_JAVA百科 new version of my app from Eclipse to my phone (I am developing and changing my database very often). What is th

I would to erase and recreate the database for my app each time I send a开发者_JAVA百科 new version of my app from Eclipse to my phone (I am developing and changing my database very often). What is the easiest way to do this?


public class DatabaseHelper extends SQLiteOpenHelper {

public DatabaseHelper(Context context) {
    super(context, dbName, null, 1);

}
@Override
public void onCreate(SQLiteDatabase db) {   
    db.execSQL("CREATE TABLE USERS (username TEXT, password TEXT);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
    db.execSQL("DROP TABLE IF EXISTS USERS");
    onCreate(db);
}

i use this one in my code :) change super(context, dbName, null, <database version number>); and it will execute onUpgrade method.


If this is something you do not wish to do once it is live, you can just clear data from your application manager each time. Also, you can make the database version number different and have the onUpgrade destroy and recreate the DB

private static final String DATABASE_NAME = "MyDbName";
private static final int DATABASE_VERSION = 6; 
private static class DbOpenHelper extends SQLiteOpenHelper{

public DbOpenHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    onUpgrade(this.getWritableDatabase(), 0, 0); 
        // 
    }

   @Override
   public void onCreate(SQLiteDatabase db) {
       db.execSQL(TableHelper1.CREATE_TABLE_QUERY);
   }

   @Override
   public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
      db.execSQL("DROP TABLE IF EXISTS "+ TableHelper1.TABLE_NAME);

      onCreate(db); 
   }

}


In Eclipse, go into Debug Configurations, then Android Application on the left hand side. Select the debug configuration that you are using and then select the Target tab.

At the bottom, you'll see a checkbox labeled "Wipe User Data".

If you check that, everytime you launch the simulator, the data associated with your application (including the SQLite database) will be erased.

Your application will then call onCreate() for your SQLiteOpenHelper, and your database will be recreated.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号