0

我的资产文件夹中有我的 sqlite 数据库。数据库被称为 foo.db 当我去测试我的应用程序时,无论是在模拟器还是我的设备上,它总是说没有数据库存在,创建了空白数据库。我的数据库加载了数据,我想让它推送到手机或模拟器进行测试。为什么这不起作用?

下面是我的应用程序中检查数据库是否存在的部分......但它永远找不到它。我已经在调试模式下运行它并且 DB_PATH 和 DB_NAME 具有正确的值,但它仍然每次都会创建一个空数据库。

我在看什么?

/**
 * Called when the activity is first created.
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.listpage);
    this.myDbHelper = new DataBaseHelper(this);
    try {
        myDbHelper.createDataBase();
    } catch (IOException ioe) {
        throw new Error("Unable to create database");
    }
    try {
        myDbHelper.openDataBase();
    } catch (SQLException sqle) {
        throw sqle;
    }
}

/**
 * Creates a empty database on the system and rewrites it with your own database.
 */
public void createDataBase() throws IOException {
    boolean dbExist = checkDataBase();
    if (dbExist) {
        //do nothing - database already exist
        System.out.println("DB alrady exists  comment this out before your deply");
    } else {
        System.out.println("an empty DB is beng created  comment this out before your deply");
        //By calling this method an empty database will be created into the default system path
        //of your application so we are gonna be able to overwrite that database with our database.
        this.getReadableDatabase();
        try {
            copyDataBase();
        } catch (IOException e) {
            throw new Error("Error copying database");
        }
    }
}


/**
 * Check if the database already exist to avoid re-copying the file each time you open the
 * application.
 *
 * @return true if it exists, false if it doesn't
 */
private boolean checkDataBase() {
    SQLiteDatabase checkDB = null;
    try {
        String myPath = DB_PATH + DB_NAME;
        checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
    } catch (SQLiteException e) {
        //database does't exist yet.
    }

    if (checkDB != null) {
        checkDB.close();
    }
    return checkDB != null ? true : false;
}
4

0 回答 0