使用ormlite-android创建自定义Dao时出现空指针异常

时间:2013-02-15 07:21:39

标签: ormlite

我正在尝试扩展基础ORMLite DAO类,以便我可以添加一些自定义方法。我试过这里的答案,但我得到一个空错误,不知道如何正确地转换dao对象(Ormlite - Constructor call failing when BaseDaoImpl is extended)目前,我有下表:

@DatabaseTable(tableName="beers", daoClass=BeerDao.class)
public class Beer {
    public static final String BEER_NAME = "name";

    @DatabaseField(generatedId = true)
    private UUID id = UUID.randomUUID();

    @DatabaseField()
    private String name;

    @DatabaseField()
    private String breweryName;

    public Beer() {}

    ... getters/setters
    }

BeerDao班:

public class BeerDao<Beer,UUID> extends BaseDaoImpl<Beer,UUID> {

    public BeerDao(ConnectionSource connectionSource, Class<Beer> dataClass) throws SQLException {
        super(connectionSource, dataClass);
    }
}

DatabaseHelper代码:

public class DatabaseHelper extends OrmLiteSqliteOpenHelper  {
    private static final String TAG = "Database";

    private static final String DATABASE_NAME = "brewgenius.db";
    private static final int DATABASE_VERSION = 7;

    private BeerDao<Beer, UUID> beerDao = null;
    private Dao<Checkin, UUID> checkinDao = null;

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION, R.raw.ormlite_config);
    }

    /* ... onCreate and onUpgrade code ..*/

    /**
     * Get Beer Model DAO
     * 
     * @return Beer DAO
     */
    public BeerDao<Beer, UUID> getBeerDao() {
        if (beerDao == null) {
            try {
                beerDao = getDao(Beer.class);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return beerDao;
    }

}

在我的活动中,当我尝试获取Dao时,我得到一个空指针异常。

BeerDao<Beer,UUID> dao = getHelper().getBeerDao();

仅供参考,Dao被投射到:

BeerDao<Beer,UUID>

更新

看起来我的DatabaseConfigUtil没有读取DaoClass属性。

public class DatabaseConfigUtil extends OrmLiteConfigUtil {
    public static void main(String[] args) throws SQLException, IOException {
        writeConfigFile("ormlite_config.txt");
    }
}

从DatabaseHelper的constuctor中删除ormlite_config.txt导致动态读取正确读取DaoClass属性。不知道作家为什么不写这个?

这是ormlite_config.txt

# --table-start--
dataClass=com.brewgenius.model.Beer
tableName=beers
# --table-fields-start--
# --field-start--
fieldName=id
columnName=_id
generatedId=true
# --field-end--
# --field-start--
fieldName=name
# --field-end--
# --field-start--
fieldName=breweryName
# --field-end--
# --table-fields-end--
# --table-end--
#################################

0 个答案:

没有答案