2013-07-02 31 views
0

我想在android中使用ORMLite預先存在的數據庫文件。我有已經創建數據庫的database.db文件。我想在我的應用程序中使用它。如何使用ORMLite將預先存在的數據庫讀入Android

我的課程擴展了OrmLiteSqliteOpenHelper。

任何人都有想法嗎?請幫助

我使用的數據庫文件複製到使用
公共靜態無效copyDataBase(字符串路徑,上下文C)數據路徑拋出IOException異常{

//Open your local db as the input stream 
    InputStream myInput = c.getAssets().open("Mydb.db"); 

    // Path to the just created empty db 
    String outFileName = "/data/data/packageName/databases/databaseName"; 
    String outFileName2 = "/data/data/packageName/databases/"; 
    File file = new File(outFileName2); 
    if(!file.exists()) 
     file.mkdirs(); 
    //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(); 
} 

,但它不會幫助我。

+0

那你試試,到目前爲止,並沒有你會得到什麼錯誤? – Qben

回答

0

這是一種在黑暗中刺傷,因爲我不知道你的確切問題是什麼,但你不能只在OrmLiteSqliteOpenHelper構造函數中指定數據庫文件(和路徑)?

OrmLiteSqliteOpenHelper(android.content.Context context, String databaseName, android.database.sqlite.SQLiteDatabase.CursorFactory factory, int databaseVersion)

也有一些關於這個論壇,與打開自定義數據庫文件的處理問題。 This問題不是ORMLite的具體問題,但它可能會讓你轉發,因爲它打開了一個自定義的數據庫文件。

希望這個幫助你有點在路上。

0

我已經解決了這個問題,下面執行

try { 

      String destPath = "/data/data/" + context.getPackageName() 
        + "/databases"; 
      Log.v("LOG", destPath); 

      File f = new File(destPath); 
      if (!f.exists()) { 
       f.mkdirs(); 
       File outputFile = new File("/data/data/" 
         + context.getPackageName() + "/databases", 
         "Name ofyour Database"); 
       outputFile.createNewFile(); 

       String DatabaseFile = "database file name from asset folder"; 

       InputStream in = context.getAssets().open(DatabaseFile); 
       OutputStream out = new FileOutputStream(outputFile); 

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

     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      Log.v("TAG", "ioexeption"); 
      e.printStackTrace(); 
     } 
相關問題