2012-12-29 117 views
5

我在我的assets文件夾中有一個.db文件。我已將其複製到模擬器中的data/data/<packagename>/databases/文件夾中,並且其工作正常。數據庫未從資產文件夾複製到設備

但是,當我在設備上運行它時,它強制關閉。它顯示

SQLite exception: no such table: tbl_user 

這裏是我的代碼..

public class DatabaseHelper extends SQLiteOpenHelper { 

     public DatabaseHelper() { 

      super(dataContext, DATABASE_NAME, null, 1); 

      DB_PATH = "/data/data/" 
        + dataContext.getApplicationContext().getPackageName() 
        + "/databases/"; 

      Log.d("PATH", DB_PATH); 

      boolean dbExist = checkDataBase(); 
      if (!dbExist) { 

       this.getReadableDatabase(); 
       try { 
        copyDataBase(); 

       } catch (IOException e) { 
        Log.d("Error", e.toString()); 
       } 
      } 

     } 

     private void copyDataBase() throws IOException { 
      // TODO Auto-generated method stub 

      InputStream inFile = dataContext.getAssets().open(DATABASE_NAME); 
      String outFileName = DB_PATH + DATABASE_NAME; 
      OutputStream myOutput = new FileOutputStream(outFileName); 
      byte[] buffer = new byte[1024]; 
      int length; 
      while ((length = inFile.read(buffer)) > 0) { 
       myOutput.write(buffer, 0, length); 
      } 
      // Close the streams 
      myOutput.flush(); 
      myOutput.close(); 
      inFile.close(); 
     } 

     private boolean checkDataBase() { 
      // TODO Auto-generated method stub 

      File dbFile = new File(DB_PATH + DATABASE_NAME); 

      return dbFile.exists(); 

     } 

我是不是應該做些別的事情來複制數據庫的設備???

謝謝..

+2

我真的推薦使用'SQLiteAssetHelper',因爲它調試了整個進程,而不是滾動自己的:https://github.com/jgilfelt/android-sqlite-asset-helper – CommonsWare

+0

請檢查此鏈接http://www.reigndesign.com/blog/using-your-own-sqlite-database-在-Android的應用程序/ –

回答

5

得到的答覆... :)

從這裏..

http://www.anddev.org/networking-database-problems-f29/missing-table-in-sqlite-with-specific-version-of-desire-hd-t50364.html

它與2.3.6版本的問題...這是與其他設備一起工作...只需添加三條線來解決問題...

boolean dbExist = checkDataBase(); 
     SQLiteDatabase db_Read = null; 
     if (!dbExist) 
     { 
      db_Read = this.getReadableDatabase(); 
      db_Read.close(); 

      try 
      { 
       copyDataBase(); 
      } 
      catch (IOException e) 
      { 
       Log.d("Error", e.toString()); 
      } 
     } 
0

只需將資產文件夾中的數據庫文件.db擴展名更改爲.png或其他壓縮格式,它將在2.1,2.2及以上版本的設備中運行

相關問題