将OrmLiteSqliteOpenHelper与DAO类一起使用

时间:2013-01-04 19:38:17

标签: android sqlite module dao inject

我使用以下库:

ormlite-机器人-4.28.jar ormlite核心,4.28.jar roboguice-2.0.jar 吉斯-3.0-no_aop.jar 吉斯-assistedinject-3.0-rc2.jar 机器人支撑-v13.jar

我的所有注射服务都运行良好,但我遇到以下情况的问题。我创建了一个DaoProvider,如下所示;

public class DaoProvider<T extends DatabaseEntity, ID> implements Provider<Dao<T, ID>>

我的AbstractModule类看起来像这样;

bind(new TypeLiteral<Dao<CityPersist, Integer>>() {
        }).toProvider(new DaoProvider<CityPersist, Integer>(ormLiteSqliteOpenHelper.getConnectionSource(), CityPersist.class))

我的CityDao看起来像这样;

@ImplementedBy(CityDaoImpl.class)
public interface CityDao
    extends Dao<CityPersist, Long>
{
    ConnectionSource getConnectionSource();

    CityPersist create(JSONObject json);

    CityPersist findByCityId(String cityId);
}

我遇到的问题是尝试在AbstractModule中创建ConnectionSource。如果使用roboguice 1,我可以设置以下内容;

public ClientServicesModule(OrmLiteSqliteOpenHelper ormLiteSqliteOpenHelper)
    {
         super();
         this.ormLiteSqliteOpenHelper = ormLiteSqliteOpenHelper;
    }

在我的Application类中创建一个新的AbstractModule。但是,我已经看到任何允许我在roboguice 2中创建相同内容的地方。

有什么想法吗?

提前致谢。

1 个答案:

答案 0 :(得分:0)

找到解决方案;

由abstractmodules类更新,如下所示;

bind(DealsDao.class).toProvider(new DaoProvider<DealPersist, DealsDao>(OpenHelperManager.getHelper(context, DatabaseHelper.class).getConnectionSource(),Deal.class)).in(Scopes.SINGLETON);

然后我的帮助程序类看起来像这样;

public class DatabaseHelper
    extends OrmLiteSqliteOpenHelper
{

    private static final String LOG_TAG = "DatabaseHelper";
    private static final String DATABASE_NAME = "Data.db";
    private static final int DATABASE_VERSION = 1;
    private Dao<Deal, Integer> dealDAO = null;

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

    /**
     * This is called when the database is first created. Usually you should call createTable statements here to create the tables that will store
     * your data.
     */
    @Override
    public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource)
    {
        try
        {           
            TableUtils.createTable(connectionSource, Deal.class);
        }
        catch (SQLException ex)
        {           
            throw new RuntimeException(ex);
        }
    }

    /**
     * This is called when your application is upgraded and it has a higher version number. This allows you to adjust the various data to match the
     * new version number.
     */
    @Override
    public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion)
    {

    }

}

现在一切正常!它结合了不同的解决方案......