0

我正在尝试在我的 android 应用程序中使用现有的 sqlite 数据库。我已经使用这个链接创建了我的数据库,然后我把我的数据库放在

“..../assets/databases”文件夹。

这是我的 DataBaseHelper 类的构造函数:

public DataBaseHelper(Context context) {    
            super(context,  dbName , null, 3);
            this. applicationContext  = context;
            dbPath="/data/data/com.tutecircle.wordapp/databases/";
}

我使用以下代码尝试了数据库是否存在:

public boolean checkDataBase(){  
            File dbFile = new File( dbPath +  dbName);  
            return dbFile.exists();
}

上面的函数返回没有数据库和我得到的错误:

sqlite3_open_v2("/data/data/com.tutecircle.wordapp/databases/chumma", &handle, 1, NULL) sqlite 返回失败:错误代码 = 14,msg = 无法在源代码行 25502 打开文件

这就是我所说的:

 DataBaseHelper myDbHelper = new DataBaseHelper(this);
 try { myDbHelper.copyDataBase();
 myDbHelper.openDataBase();
 }catch(SQLException sqle){
 throw sqle; 
}

这是 copyDataBase 函数:

public void copyDataBase(){
 try{ InputStream assestDB = context.getAssets().open(dbName); 
OutputStream appDB = new FileOutputStream(DB_PATH,true); 
byte[] buffer = new byte[1024];
 int length; 
while ((length = assestDB.read(buffer)) > 0) {
 appDB.write(buffer, 0, length); 
} 
appDB.flush(); 
appDB.close();
 assestDB.close();
 }catch(IOException e)
{ 
e.printStackTrace(); 
} }

我的开放数据库功能:

public void openDataBase() throws SQLException{ 

if(databaseExist()){ 
Log.i("Db existing","db existing....");
 String myPath = DB_PATH + dbName; 
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY); Log.i("Db opened","db opened....");
} 
else 
Log.i("Db not existing","db not existing...."); 
}

请各位大佬,我真的不知道该怎么办。请帮助我...

4

1 回答 1

3

确保将数据库从资产文件夹复制到

/data/data/com.tutecircle.wordapp/databases/

在实例化你之前DatabaseHelper

//Open your local db as the input stream
InputStream myInput = myContext.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();

编辑:在你更新你的问题之后,看起来你正试图用一个目录而不是文件的路径来实例化FileOutputStream你的方法。copyDataBase()尝试以下操作:

InputStream assestDB = context.getAssets().open(dbName); 
OutputStream appDB = new FileOutputStream(new File(DB_PATH,dbName)); 
于 2013-09-18T12:37:09.110 回答