如何使用 ORMLite 资产中可用的数据库

How to use a database available in asset with ORMLite

我在 assets 文件夹中有一个数据库文件,当用户安装这个程序时,在第一次程序启动器中我将从 assets[=29 复制数据库=] 到程序 数据库

这是我的代码:

private static final String DATABASE_NAME= "data.db";

public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION, R.raw.ormlite_config);
    this.myContext = context;
}

/************************************************
 * Suggested Copy/Paste Done
 ************************************************/

@Override
public void onCreate(SQLiteDatabase sqliteDatabase, ConnectionSource connectionSource) {
    createDataBase();
}

public void createDataBase(){
    boolean dbExist = checkDataBase();
    if(!dbExist){
        try {
            copyDataBase();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

private boolean checkDataBase(){
    SQLiteDatabase checkDB = null;
    try{
        String myPath = myContext.getDatabasePath(DATABASE_NAME).getPath();
        checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
    }catch(SQLiteException e){
        e.printStackTrace();
    }

    if(checkDB != null){
        checkDB.close();
    }
    return checkDB != null;
}
private void copyDataBase() throws IOException{
    InputStream myInput = myContext.getAssets().open(DATABASE_NAME);
    String outFileName = myContext.getDatabasePath(DATABASE_NAME).getPath();
    File f = new File(outFileName);
    f.getParentFile().mkdirs();
    f.createNewFile();
    OutputStream myOutput = new FileOutputStream(f);

    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer))>0){
        myOutput.write(buffer, 0, length);
    }
    myOutput.flush();
    myOutput.close();
    myInput.close();
}

我检查了设备中的 databases 文件夹,发现它有 data.db 文件,但这个文件没有 table.

我用来复制数据的代码有运行.

为什么data.db是错误的?


UPDATED:

@DatabaseTable(tableName = "english")
public class Topic {
    @DatabaseField(generatedId = true, columnName = "id")
    private int id;
    @DatabaseField(columnName = "title")
    private String title;
    @DatabaseField(columnName = "question")
    private String question;
    @DatabaseField(columnName = "answer")
    private String answer;
    @DatabaseField(columnName = "audio_url")
    private String audioUrl;
    @DatabaseField(columnName = "local_url")
    private String localUrl;

    public Topic() {
    }
}
CREATE TABLE `english` (
    `id`    INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
    `title` NVARCHAR,
    `question`  NVARCHAR,
    `answer`    NVARCHAR,
    `audio_url` NVARCHAR,
    `local_url` NVARCHAR
);

super(context, DATABASE_NAME, null, DATABASE_VERSION, R.raw.ormlite_config);

称为data.db已创建。这样 onCreate 就不会被调用。 你不应该把 createDataBase 放在这里。

我想你可以把它放到 getWritableDatabasegetDao 函数中。