我在我的Android应用程序中使用OrmLite库来处理数据库。它适用于所有Android版本,但我在Android 5.1.1(API 22)上遇到了麻烦。我有一个班级DBHelper extends OrmLiteSqliteOpenHelper
。在onCreate方法中,我为我的数据库创建表
@Override
public void onCreate(SQLiteDatabase db, final ConnectionSource connectionSource)
{
try {
for (Class c : models)
TableUtils.createTableIfNotExists(connectionSource, c);
}
catch (Throwable e) {
e.printStackTrace();
Logger.e("error creating DB " + DATABASE_NAME);
}
}
变量models
是一个描述每个表的字段的类数组。
Class[] models = {
User.class,
Profile.class,
Offer.class,
Partner.class,
OfferCategory.class,
PrizeCategory.class,
...
我发现创建表OfferCategory时会出现异常java.lang.NullPointerException: Attempt to invoke interface method 'int com.j256.ormlite.field.DataPersister.getDefaultWidth()' on a null object reference
。这是我的类OfferCategory
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
@JsonIgnoreProperties(ignoreUnknown=true)
@DatabaseTable(tableName= DbHelper.TABLE_CATEGORY)
public class OfferCategory implements Serializable
{
public static final String FIELD_ID = "_id",
FIELD_ORDER = "_order";
public Bundle toBundle()
{
final Bundle b = new Bundle();
b.putSerializable(getClass().getName(), this);
return b;
}
public static final BaseModel fromBundle(final Bundle b, final Class<?> cl)
{
if (b != null && b.containsKey(cl.getName()))
{
return (BaseModel) b.getSerializable(cl.getName());
}
return null;
}
/**
*
*/
private static final long serialVersionUID = 7805031064669698244L;
@DatabaseField(unique=true, canBeNull=false, columnName=FIELD_ID, id=true)
@JsonProperty(required=true)
public int id;
@DatabaseField
public String name;
@DatabaseField(foreign=true, foreignAutoRefresh = true, foreignAutoCreate=true, foreignColumnName = FIELD_ID)
public Offer offer;
public OfferCategory()
{
}
public OfferCategory(final int id)
{
this.id = id;
}
}
我不知道为什么这段代码适用于所有Android版本,但仅在Android 5.1.1(API 22)上抛出异常。在最近的Android版本上一切正常。
请告诉我可能是什么问题?感谢。