sqlite3_open_v2(“/ data / data / com.tutecircle.wordapp / databases / chumma”,& handle,1,NULL)失败

时间:2013-09-18 09:35:14

标签: android sqlite

我正在尝试在我的Android应用中使用现有的sqlite数据库。 我使用此link创建了数据库,然后将数据库放在

  

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

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

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

我使用此代码尝试了db是否存在:

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

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

  

sqlite3_open_v2( “/数据/数据/ com.tutecircle.wordapp /数据库/ 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...."); 
}

请大家好,我真的不知道该怎么做。 plss帮助我...

1 个答案:

答案 0 :(得分: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));