安卓ORMLite出现“no such table”异常

4

我在我的安卓应用中使用ORMlite(版本4.48)。

这是我的ORMLiteHelper:

public class TrainingOrmLiteHelper extends OrmLiteSqliteOpenHelper {
public static final String TAG = TrainingOrmLiteHelper.class.getSimpleName();

public static final String DATABASE_NAME = "marek.sqlite";
public static final int DATABASE_VERSION = 7;

private Dao<DataModel, Integer> modelDao = null;

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

@Override
public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
    try {
        TableUtils.clearTable(connectionSource, DataModel.class);
        Log.d(TAG, "Created");
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

@Override
public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {
    try {
        TableUtils.dropTable(connectionSource, DataModel.class, true);
        Log.d(TAG, "Updated");
    } catch (SQLException e) {
        e.printStackTrace();
    }
    onCreate(database, connectionSource);
}

public Dao<DataModel, Integer> getModelDao() throws SQLException {
        if (modelDao == null) {
            modelDao = getDao(DataModel.class);
        }
        return modelDao;
    }
}

以及我的数据模型对象类

    @DatabaseTable(tableName = "data_model")
    public class DataModel {

    @DatabaseField(generatedId = true)
    int id;

    @DatabaseField
    String title;

    @DatabaseField
    String description;

    public DataModel() {
    }

    public DataModel(String title, String description) {
        this.title = title;
        this.description = description;
    }

}

当我尝试对我的数据进行操作时,比如说:
TrainingOrmLiteHelper helper = new TrainingOrmLiteHelper(this);
        DataModel item = new DataModel();
        item.description = "ELO";
        item.title = "blah blah";
        helper.getModelDao().create(item);

我收到了错误:
E/SQLiteLog﹕ (1) no such table: data_model
1个回答

5

看一下你的代码,你其实还没有创建这张表,你需要在OrmLiteSqliteOpenHelper类的onCreate方法中添加createTableIfNotExist

TableUtils.createTableIfNotExists(ConnectionSource connectionSource, Class<T> dataClass);

它起作用了,我有一个清空表而不是创建表!非常感谢你!! - Mark

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接