我如何知道何时更新数据库 - Android

Tof*_*ira 0 java sqlite android

嘿,我正在构建一个包含数据库的Android应用程序.我的问题是如何知道应用程序是否已更新?我的意思是,我知道当DATABASE_VERSION来自 - 时调用onUpgrade方法 -

public DataBaseHelper(Context context) {        
    super(context, DB_NAME, null, DATABASE_VERSION);
    this.myContext = context;
}
Run Code Online (Sandbox Code Playgroud)

低于应用程序的版本,但如何在更新后增加它,因此应用程序不会一直更新自己?

Ste*_*han 6

您无需记录版本号.在调用onUpgrade()之后,android会自动处理所有这些内容.当下一次更新到期时(即再次增加DATABASE_VERSION),将自动调用onUpgrade().

更清楚一点:static final int DATABASE_VERSION每次更改数据库结构中必不可少的内容时,只需保留一个在开发时增加的字段.

您创建了一个扩展SQLLiteOpenHelper的类,它基本上如下所示:

public class ContentDatabase extends SQLiteOpenHelper {

  // Whenever you change the DB structure, increment DATABASE_VERSION (it starts from 1, so  your first upgrade should be 2)
  // - note it's only used for upgrades; if it's a new install, onUpgrade won't be called and everything is done by onCreate instead
  private static final int DATABASE_VERSION = 6;

  public ContentDatabase(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
  }

  public void onCreate(SQLiteDatabase db) {
    // Code to create the most recent version of your database 
    // i.e. CREATE TABLE xxx (....) 
  }

  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Code to update an existing database structure to the most recent 
    // version. 

    if (oldVersion < 2) {
      // do something to upgrade the DB to version 2
    }

    if (oldVersion < 3) {
      // do something to upgrade the DB to version 3
    }

    if (oldVersion < 6) {
      // Let's assume you added a new table in v4, and then added a field to that new table in v6
      if (oldVersion < 4) {
        // add the v6 version of the new table to the DB
      }
      else {
        // add the new field to the existing v4 table in the DB
      }
    }

  }
}
Run Code Online (Sandbox Code Playgroud)

每当您需要更改表的结构(即添加aditional列或表)时,您将DATABASE_VERSION变量增加1并相应地为onCreate()和onUpdate()方法编写代码.这些方法由android自动调用.