4

我正在使用 android 和 ormlite。我在初始化ForeignCollection.

我发现了这个,初始化它:dao.getEmptyForeignCollection()

但是对于 dao,我需要DatabaseHelper,对于 databasehelper,我需要 applicationContext,但在实体中我没有上下文。还有其他选择吗?

这就是代码,它是 1:n 的关系。班组:

@DatabaseField(canBeNull = true, foreign = true)
private Club club;

班级俱乐部:

@DatabaseField(canBeNull = true, foreign = true)
private ForeignCollection<Team> teams;

感谢帮助

4

2 回答 2

2

您的问题不是关于外国收藏,而是关于ORMLite如何在 Android 下连接。所有这些都在文档中进行了解释:

http://ormlite.com/docs/android

你特别问:

但是对于 dao,我需要DatabaseHelper,对于数据库助手,我需要应用程序Context,但在实体中我没有上下文。还有其他选择吗?

在 Android 下,每个扩展Activity, ListActivity, Service, and TabActivity also的类都是一个Context. 您可以从在线文档中查看类层次结构:

java.lang.Object
    ↳ android.content.Context
        ↳ android.content.ContextWrapper
            ↳ android.view.ContextThemeWrapper
                ↳ android.app.Activity

如果您查看网站上提供的Android 示例项目,您可以了解 Android 应用程序的连接方式:

  • 你的主要Activity延伸OrmLiteBaseActivity

    public class HelloAndroid extends OrmLiteBaseActivity<DatabaseHelper> {
    
  • 中的onCreate方法OrmLiteBaseActivity构造您DatabaseHelper使用 ORMLiteOpenHelperManager及其本身作为Context

    OpenHelperManager.getHelper(this.getApplicationContext());
    
  • 您可以使用该OrmLiteBaseActivity.getHelper()方法访问帮助程序来创建您的 DAO,以便您可以将内容持久保存到数据库中。

于 2012-04-11T12:39:25.377 回答
1

您需要注入所需的依赖项。

如果您的实体需要数据库助手,请提供。如果您的数据库助手需要上下文,请提供它。

为您的类提供构造函数,使所需的依赖项成为强制性的:

public DataHelper( Context context ) {
  this.context = context;
}

然后,从您的活动或应用程序模型中,使用

new DataHelper( this );

注入依赖项。

先验地,使用将为您的数据库助手提供一般上下文的应用程序类会很有趣,而不是在其 onCreate 方法中为每个活动创建一个新的数据库助手。

于 2012-04-11T10:34:42.213 回答