2015-01-07 10 views
0

我試圖通過下載它並將它解壓縮到正確的位置來將SQLite數據庫傳輸到應用程序中。解壓縮後,我成功傳輸了數據庫。我得到的錯誤是它找不到我查詢的任何表。我也成功地解壓縮和閱讀正常的文本文件。在Android中解壓縮的數據庫不可讀

該數據庫有希伯來語和英語,但這並沒有造成問題。雙語數據庫在沒有壓縮的情況下被成功複製,並且雙語文本已被成功解壓縮和讀取。儘管如此,仍有可能出現編碼問題。這對我來說似乎很奇怪,因爲正如你可以在代碼中看到的那樣,我只是直接複製字節。

-EDIT-

假設預編譯的數據庫名爲test1.db。我將它壓縮,放入應用程序,解壓縮並調用test2.db。當我在這兩者上運行diff命令時,沒有任何區別。所以必須有一個技術問題的方式android讀取文件/或可能編碼問題在android上不存在的電腦上?

我討厭做代碼轉儲,但我會發布我的copyDatabase()函數(它的工作原理)。這是我以前在解壓縮的DB文件上運行它的原因。我把它放在這裏作爲比較。現在我試圖使用unzipDatabase()函數(這不起作用),並將其用於壓縮的DB文件。後者的功能是從How to unzip files programmatically in Android?

private void copyDatabase() throws IOException{ 
    String DB_NAME = "test.db"; 
    String DB_PATH = "/data/data/org.myapp.myappname/databases/"; 
    //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(); 
} 

private boolean unzipDatabase(String path) 
{  
    String DB_NAME = "test.zip"; 
    InputStream is; 
    ZipInputStream zis; 
    try 
    { 
     String filename; 
     is = myContext.getAssets().open(DB_NAME); 
     zis = new ZipInputStream(is);   
     ZipEntry ze; 
     byte[] buffer = new byte[1024]; 
     int count; 

     while ((ze = zis.getNextEntry()) != null) 
     { 
      // write to a file 
      filename = ze.getName(); 

      // Need to create directories if not exists, or 
      // it will generate an Exception... 
      if (ze.isDirectory()) { 
       Log.d("yo",path + filename); 
       File fmd = new File(path + filename); 
       fmd.mkdirs(); 
       continue; 
      } 

      OutputStream fout = new FileOutputStream(path + filename); 

      // reading and writing zip 
      while ((count = zis.read(buffer)) != -1) 
      { 
       fout.write(buffer, 0, count);    
      } 

      fout.flush(); 
      fout.close();    
      zis.closeEntry(); 
     } 

     zis.close(); 
    } 
    catch(IOException e) 
    { 
     e.printStackTrace(); 
     return false; 
    } 

    return true; 
} 
+0

是啊,我又能夠複製和讀取數據庫時,它解壓縮(在Windows)。但是當我在android手機上解壓縮時,它找不到表格,這表明整個文件可能未被正確複製 – Bob

+0

'copyDatabase()'方法不是必需的(時間浪費),因爲您可以使用'unzipDatabase()'方法直接將數據庫提取到正確的路徑中(只需添加一個String參數和目標路徑)。 –

+0

也不硬編碼DB_PATH ...使用像assetsdbhelper這樣的庫(類似的東西)......如果db在設備上是隻讀的,你可以考慮使用某種同步(從服務器的一種方式很容易實現,兩種方式都是痛苦中的HTTP + JOSN作爲中介 – Selvin

回答

0

複製所以還是不知道爲什麼,但如果我先刪除數據庫(位於DB_PATH + DB_NAME)的舊副本的問題就解決了,然後解壓新那裏。直接複製時,我不需要這樣做。

如此耶,這是一個文件覆蓋的問題......如果有人知道這是爲什麼,隨意評論