ActiveAndroid 使用现有数据库

ActiveAndroid using exist database

我正在使用 ActiveAndroid as a third party library in order to working with sqlite database in android, i don't have any problem with creating and using new databases with this library, but i don't know how can i use my own exist database with this library?i want to put my own database into assets folder and load it into ActiveAndroid 库。

public class Application extends com.activeandroid.app.Application
{

    @Override
    public void onCreate()
    {
        super.onCreate();
        createDatabase();
    }

    private void createDatabase()
    {
        Configuration dbConfiguration = new Configuration.Builder(this).setDatabaseName("dastan.db").create();
        ActiveAndroid.initialize(dbConfiguration);

    }


    @Override
    public void onLowMemory()
    {
        android.os.Process.killProcess(android.os.Process.myPid());
        super.onLowMemory();
    }
}

"xArthasx" 在 Issue 41 中说:

If you have the file (sqlite database) and the tables keep the same structure as the class you made in java, you should be able use the database by coping the file (sqlite database) to the assets directory (project directory) and set the AA_DB_NAME equals to the name of the file.

如果现有数据库不是用ActiveAndroid创建的,您可能需要迁移数据;参见 Use ActiveAndroid on existing database-content

据此 official document

您可以按照以下步骤使用 pre-populated 数据库:

将 SQLite 数据库文件的副本放在应用程序的资产目录中,例如:

/myapp/src/main/assets/prepop.db

确保在清单文件中设置 AA_DB_NAME,例如:

<meta-data android:name="AA_DB_NAME" android:value="prepop.db" />

现在,当您部署应用程序时,它会将 prepop.db 文件从资产目录复制到 /data/data/myapp/databases storage.

注意:这将导致数据库重复,因为它将与 APK 一起打包并复制到存储目录。 确保数据库与 ActiveAndroid

一起正常工作

要确保数据库与 ActiveAndroid 一起正常工作,请执行以下步骤:

设置 android_metadata table

CREATE TABLE "android_metadata" ("locale" TEXT DEFAULT 'en_US')

INSERT INTO "android_metadata" VALUES ('en_US')

如果您没有为模型定义 id 列名称,请确保将主键重命名为默认值 Id,而不是 Android 数据库的标准 _id。但是,如果你的数据要显示在ListViews中,建议将你的主键列定义为_id。您只需在模型的 @Table 注释中添加 id = "_id" 参数即可,如下所示:

@Table(name = "Items", id = "_id")
public class Item extends Model {