【问题标题】:What does the SQLiteOpenHelper class do with the context parameter?SQLiteOpenHelper 类对 context 参数做了什么?
【发布时间】:2012-06-22 09:49:21
【问题描述】:

我正在扩展SQLiteOpenHelper 类。我的构造函数是

public MyDatabaseHelper(Context context) {
    super(
        context,         // ???
        "MyDatabase.db", // Database name
        null,            // Cursor factory
        1                // database version
    );
}

SQLiteOpenHelper 构造函数如何处理上下文信息?

对于我的应用程序,无论程序状态(上下文)如何,构造函数的行为都相同。我可以为上下文传递 null 而不会有任何未来问题吗?

【问题讨论】:

    标签: android database sqlite constructor


    【解决方案1】:

    如果您提供空值,它将创建一个内存数据库,但您还需要为数据库名称参数提供空值,以便正确处理。

    这在上下文的构造函数文档中有记录

    用于打开或创建数据库的上下文数据库的名称 文件,或者为内存数据库为空

    另外,如果你查看 SQLiteHelper 类本身的源代码,你会看到它使用 mName 值来决定是否使用 mContext。在线查看源代码:

    http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.0.4_r1.2/android/database/sqlite/SQLiteOpenHelper.java#SQLiteOpenHelper.0mContext

    【讨论】:

    • 谢谢!这现在更有意义了。我从来没有听说过 grepcode,我想我和那个网站会很熟悉!
    • 菜鸟问题:数据库名称不是已经用于第二个参数了吗?那么上下文会涉及什么?
    • 上下文可以是活动或应用程序本身。
    • 来自源代码:上下文用于:1)获取数据库的完整路径。 2) 在上下文对象上调用 openOrCreateDatabase。
    猜你喜欢
    • 2021-05-06
    • 1970-01-01
    • 1970-01-01
    • 2021-04-26
    • 1970-01-01
    • 2020-09-08
    • 2016-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多