与升级 ORMLite 模式混淆

Confusing with upgrading ORMLite schema

我在 table account 中添加了一列 (description)。我还阅读了 this guild 来升级我的数据库。但是,我对这段代码中的 getHelper() 方法有点困惑:

Dao<Account, Integer> dao = getHelper().getAccountDao();
// change the table to add a new column named "description" 
dao.executeRaw("ALTER TABLE `account` ADD COLUMN description INTEGER;");

它是从哪里来的?我没有看到我的 DatabaseHelper class 中声明了 getHelper()。有人可以帮助我吗?

您应该有一个 class 扩展 OrmLiteSqliteOpenHelper,您可以在其中创建表(在 onCreate 中)并更新它们(在 onUpgrade 中):

public class DatabaseHelper extends OrmLiteSqliteOpenHelper {

    public DatabaseHelper(Context context) {
        super(context, "database.db", null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
        try {
           TableUtils.createTable(connectionSource, Account.class);
        } catch (SQLException e) {
            throw new RuntimeException("Error when create database tables", e);
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {
        database.execSQL("ALTER TABLE `account` ADD COLUMN description INTEGER;");

        //same as:
        //AccountDAO dao = getDao(Acount.class);
        //dao.executeRaw("ALTER TABLE 'account' ADD COLUMN description INTEGER;");
    }
}

OrmLiteBaseListActivity, OrmLiteBaseService and OrmLiteBaseTabActivity provide a method getHelper to access the database helper whenever it is needed and will automatically create the helper in the onCreate() method and release it in the onDestroy() method.

此外,如果你使用上面的classes,你应该有这样的东西:

public class MyACtivity extends OrmLiteBaseActivity<DatabaseHelper> {

    //In this class, you can call getHelper() to obtain the DatabaseHelper instance 

}