SQLiteAssetHelper NullPointerException 在 getReadableDatabase()

SQLiteAssetHelper NullPointerException at getReadableDatabase()

因为 @CommonsWare suggested (in the comments to this answer) using the Android SQLiteAssetHelper library, I decided not to use Using your own SQLite database in Android applications 方法(一个流行的 SO 答案)将我预先填充的数据库从我的资产文件夹复制到应用程序数据库文件夹。

Android SQLiteAssetHelper directions 之后,我这样设置我的项目:

因为我使用的是 gradle,所以我的数据库在 src/main/assets/databases/test.db.zip

我使用了 .zip 扩展名,因为说明上说

Earlier versions of this library required the database asset to be compressed within a ZIP archive. This is no longer a requirement, but is still supported. Applications still targeting Gingerbread (API 10) or lower should continue to provide a compressed archive to ensure large database files are not corrupted during the packaging process.

我想支持 android 的早期版本。

我的数据库class类似于以下内容:

public class MyDatabase extends SQLiteAssetHelper {

    private static final String DATABASE_NAME = "test.db.zip";
    private static final int DATABASE_VERSION = 1;

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

同样,我对 DATABASE_NAME 值使用了 .zip 扩展名,因为说明中说

...you must provide...a SQLite database inside the databases folder whose file name matches the database name you provide in code (including the file extension, if any)

但是,当我这样做时 SQLiteDatabase db = getReadableDatabase(); 我得到一个 NullPointerException。有什么问题?

这些 SO 问题和答案不是同一个问题:

我设置问题是为了让答案更明显,但这里是:

与 Android SQLiteAssetHelper 说明听起来像的相反(无论如何,在撰写本文时。希望他们将来会澄清它们),DATABASE_NAME 值不应包括.zip 扩展名。将您的代码更改为

 private static final String DATABASE_NAME = "test.db"; // no .zip extension

但保持 src/main/assets/databases/test.db.zip 不变,一切都应该正常。