У меня была такая же проблема, и я в итоге создал OrmLiteActivityListener, чтобы прослушивать мой RoboActivity и обрабатывать возникающие события.
public class RoboOrmActivityBase<H extends IOrmLiteSqliteOpenHelper> extends RoboActivity {
@Inject RoboOrmLiteActivityListener<H> OrmActivityListener;
/*
* Get a helper for this action.
*/
public H getHelper() {
return OrmActivityListener.getHelper();
}
/**
* Get a connection source for this action.
*/
public ConnectionSource getConnectionSource() {
return OrmActivityListener.getHelper().getConnectionSource();
}
}
Класс RoboOrmLiteActivityListener был получен из класса OrmLiteActivityBase.
Я удалил его наследство и заставил его слушать.
public class RoboOrmLiteActivityListener<H extends IOrmLiteSqliteOpenHelper> {
private volatile H helper;
private volatile boolean created = false;
private volatile boolean destroyed = false;
OrmLiteSqliteOpenHelperProvider databaseHelperProvider;
@Inject
public RoboOrmLiteActivityListener(OrmLiteSqliteOpenHelperProvider databaseHelperProvider) {
this.databaseHelperProvider = databaseHelperProvider;
}
/**
* Get a helper for this action.
*/
public H getHelper() {
if (helper == null) {
if (!created) {
throw new IllegalStateException("A call has not been made to onCreate() yet so the helper is null");
} else if (destroyed) {
throw new IllegalStateException(
"A call to onDestroy has already been made and the helper cannot be used after that point");
} else {
throw new IllegalStateException("Helper is null for some unknown reason");
}
} else {
return helper;
}
}
/**
* Get a connection source for this action.
*/
public ConnectionSource getConnectionSource() {
return getHelper().getConnectionSource();
}
// As you might expect, some events can have parameters. The OnCreate event
// has the savedInstanceState parameter that Android passes to onCreate(Bundle)
public void onCreate(@Observes OnCreateEvent onCreate) {
//Ln.d("onCreate savedInstanceState is %s", onCreate.getSavedInstanceState())
if (helper == null) {
helper = getHelperInternal();
created = true;
}
}
public void onDestroy(@Observes OnDestroyEvent onDestroy) {
releaseHelper(helper);
destroyed = true;
}
/**
* This is called internally by the class to populate the helper object instance. This should not be called directly
* by client code unless you know what you are doing. Use {@link #getHelper()} to get a helper instance. If you are
* managing your own helper creation, override this method to supply this activity with a helper instance.
*
* <p>
* <b> NOTE: </b> If you override this method, you most likely will need to override the
* {@link #releaseHelper(OrmLiteSqliteOpenHelper)} method as well.
* </p>
*/
private H getHelperInternal() {
@SuppressWarnings("unchecked")
H newHelper = (H) databaseHelperProvider.get();
return newHelper;
}
/**
* Release the helper instance created in {@link #getHelperInternal(Context)}. You most likely will not need to call
* this directly since {@link #onDestroy()} does it for you.
*
* <p>
* <b> NOTE: </b> If you override this method, you most likely will need to override the
* {@link #getHelperInternal(Context)} method as well.
* </p>
*/
private void releaseHelper(H helper) {
OpenHelperManager.releaseHelper();
helper = null;
}
}
Затем у меня есть DatabaseHelperProvider, который предоставляет мой Helper, который выходит из OrmLiteSqliteOpenHelper. Этот провайдер вручную выполняет инъекцию моего помощника после извлечения его из OpenHelperManager.
public class OrmLiteSqliteOpenHelperProvider implements Provider<OrmLiteSqliteOpenHelper> {
private final Context context;
private final Injector injector;
@Inject
public OrmLiteSqliteOpenHelperProvider(Context context, Injector injector) {
this.context=context;
this.injector=injector;
}
public OrmLiteSqliteOpenHelper get() {
//The OpenHelperManager built the DatabaseHelper, not us. So we need to guice it up manually.
//Guice normally does its injections when it does its constructions.
OrmLiteSqliteOpenHelper dbhelp = OpenHelperManager.getHelper(context);
injector.injectMembers(dbhelp);
return dbhelp;
}
}
У меня также есть интерфейс с именем IOrmLiteSqliteOpenHelper, который содержит члены, извлеченные из OrmLiteSqliteOpenHelper. Затем, когда я создаю свой интерфейс (IDatabaseHelper) для моего помощника, который происходит от OrmLiteSqliteOpenHelper, я могу расширяться от IOrmLiteSqliteOpenHelper.
Тогда для привязки в моем модуле у меня есть
static {
OpenHelperManager.setOpenHelperClass(DatabaseHelper.class);
}
и
@SuppressWarnings("unchecked")
private void bindDataHelperProvider() {
bind(IDatabaseHelper.class)
.toProvider((Class<? extends Provider<? extends IDatabaseHelper>>) OrmLiteSqliteOpenHelperProvider.class);
}
Тогда в моей Деятельности все для RoboGuice и Ormlite обрабатывается полностью в базовом классе и выглядит так:
public class MyActivity extends RoboOrmActivityBase<IDatabaseHelper> {
List<IMyEntity> lis;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.routine);
try {
Dao<IMyEntity,Integer> myDao = getHelper().getMyDao();
lis = myDao.queryForAll();