我需要在RemoteViewFactory类中从数据库加载数据,我使用的是OrmLite。我有一个Helper类:
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static final String DATABASE_NAME = "gfkksa.db";
private static final int DATABASE_VERSION = 1;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
try {
TableUtils.createTable(connectionSource, Issue.class);
TableUtils.createTable(connectionSource, IssuePriority.class);
} catch (SQLException e) {
Log.e(DatabaseHelper.class.getName(), "Can't create database.");
throw new RuntimeException(e);
} catch (java.sql.SQLException e) {
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource,
int oldVersion, int newVersion) {
try {
TableUtils.dropTable(connectionSource, Issue.class, true);
TableUtils.dropTable(connectionSource, IssuePriority.class, true);
onCreate(db, connectionSource);
} catch (SQLException e) {
Log.e(DatabaseHelper.class.getName(), "Can't drop databases.");
throw new RuntimeException(e);
} catch (java.sql.SQLException e) {
e.printStackTrace();
}
}
public HashMap<String, Dao> getDaoFactory() {
HashMap<String, Dao> hashFactory = new HashMap<String, Dao>();
try {
hashFactory.put("issue", getDao(Issue.class));
hashFactory.put("issuePriority", getDao(IssuePriority.class));
} catch (java.sql.SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return hashFactory;
}
}一切正常,在Activity类(extends OrmLiteBaseActivity<DatabaseHelper>)中,例如我从DB获取数据列表,如下所示:
ArrayList items = (ArrayList) getHelper().getDaoFactory().get("issue").queryForAll();但是,如果我在实现RemoteViewsService.RemoteViewsFactory (AppWidget的ListView的远程视图工厂)的类上执行相同的操作,应用程序崩溃,并显示以下异常消息:
03-18 16:13:29.244: E/AndroidRuntime(28500): java.lang.RuntimeException: Unable to bind to service cz.testbrana.widget.WidgetService@41e34110 with Intent { dat=intent: cmp=cz.testbrana.ebranasystem/cz.testbrana.widget.WidgetService (has extras) }: java.lang.IllegalStateException: A call has not been made to onCreate() yet so the helper is null如何在AppWidget的RemoteViewFactory中使用OrmLite?
发布于 2014-04-04 05:27:46
我发现,当使用官方文档(http://ormlite.com/docs/android)中的getHelper()和onDestroy()方法而不是扩展DBHelper时,一切都很好。
private DatabaseHelper databaseHelper = null;
@Override
protected void onDestroy() {
super.onDestroy();
if (databaseHelper != null) {
OpenHelperManager.releaseHelper();
databaseHelper = null;
}
}
private DBHelper getHelper() {
if (databaseHelper == null) {
databaseHelper =
OpenHelperManager.getHelper(this, DatabaseHelper.class);
}
return databaseHelper;
}https://stackoverflow.com/questions/22483543
复制相似问题