【发布时间】:2015-01-05 13:26:22
【问题描述】:
我有一个名为 example.db 的外部 sqlite 数据库,我正在尝试使用 OrmLite 创建它。我在网上搜索了一些,大家都推荐了这个教程http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/
所以我遵循它并且工作得很好,但是当我尝试使用 OrmLite 做同样的事情时,我无法从外部文件(example.db)创建我自己的数据库。我发现当我调用方法 createDatabase() 时,数据库已经创建,并且在我使用没有 OrmLite 的 OpenHelperDatabase 时没有发生。
有人知道吗?
代码是:
//imports
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static String DB_PATH = "/data/data/com.example/databases/";
private static String DB_NAME = "example.db";
private static final int DATABASE_VERSION = 1;
private SQLiteDatabase exampleDB;
private final Context context;
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, DATABASE_VERSION);
this.context = context;
}
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if(dbExist){
Log.i(DatabaseHelper.class.getName(), "Database already exist!!! Here is the problem");
}else{
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
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;
}
private void copyDataBase() throws IOException{
//Open your local db as the input stream
InputStream myInput = context.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
@Override
public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
Log.i(DatabaseHelper.class.getName(), "onCreate");
try {
createDataBase();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) {
//TODO
}
@Override
public synchronized void close() {
if(exampleDB != null)
exampleDB.close();
super.close();
}
}
【问题讨论】:
-
私有静态字符串 DB_NAME = "example";应该是私有静态字符串 DB_NAME = "example.sqlite";
-
你能读取example.db文件吗
-
@BhavikMehta 我已经尝试更改它,但它会出现相同的错误“数据库已存在”
-
@AshishTamrakar 我无法阅读 example.db
标签: android sqlite android-sqlite ormlite