2012-05-23 56 views
1

我是android開發新手。現在即時嘗試使用sqlite數據庫。我使用sqlite管理器創建了一個數據庫sqlite文件。 我曾嘗試下面的代碼,它工作在模擬器罰款,但如果我在裝置了發佈應用程序崩潰,即,它顯示一條警告消息CheckMobileForDatabase意外停止的應用程序,我的SDK版本是2.2(8)Android中導入數據庫的問題

private void StoreDatabase() { 
File DbFile=new File("data/data/com.sqldemo/databases/idua1"); 
if(DbFile.exists()) 
{ 
    System.out.println("file already exist ,No need to Create"); 
} 
else 
{ 
    try 
    { 
     DbFile.createNewFile(); 
     System.out.println("File Created successfully"); 
     InputStream is = this.getAssets().open("idua1.sqlite"); 
     FileOutputStream fos = new FileOutputStream(DbFile); 
     byte[] buffer = new byte[1024]; 
      int length=0; 
      while ((length = is.read(buffer))>0) 
      { 
      fos.write(buffer, 0, length); 
      } 
     System.out.println("File succesfully placed on sdcard"); 
      //Close the streams 
      fos.flush(); 
      fos.close(); 
      is.close(); 
    } 
    catch (IOException e) 
    { 
     e.printStackTrace(); 
    } 
    }  
    } 
+1

請張貼logcat的表現錯誤。 – Barak

+0

上面的代碼在模擬器中工作正常,但我釋放該項目它在模擬器中正常工作,應用程序崩潰,它顯示一條警報消息應用程序CheckMobileForDatabase已意外停止。解決此問題 – NAZIK

+0

因此,使用插入的手機運行它,然後抓住logcat,當它崩潰併發布。沒有看到*爲什麼*它失敗了,我們什麼也做不了,因爲您發佈的代碼中沒有任何明顯的內容。 – Barak

回答

0

沒有你的logcat的,這只是拍攝在黑暗中。

你可以嘗試檢查文件是否存在另一種方式:

private static boolean checkDataBase(String dbname) { 
    SQLiteDatabase checkDB = null; 
    boolean exist = false; 
    try { 
     String db = MAIN_DB_PATH + dbname; 
     checkDB = SQLiteDatabase.openDatabase(db, null, 
       SQLiteDatabase.OPEN_READONLY); 
    } catch (SQLiteException e) { 
     Log.v("db log", "database does't exist"); 
    } 
    if (checkDB != null) { 
     exist = true; 
     checkDB.close(); 
    } 
    return exist; 
} 

然後運行另一種方法來複制數據庫,如果不存在的話:

private static void copyDataBase(String dbname) throws IOException { 
    InputStream myInput = mCtx.getAssets().open(dbname); 
    String outFileName = MAIN_DB_PATH + dbname; 
    OutputStream myOutput = new FileOutputStream(outFileName); 
    byte[] buffer = new byte[1024]; 
    int length; 
    while ((length = myInput.read(buffer)) > 0) { 
     myOutput.write(buffer, 0, length); 
    } 
    myOutput.flush(); 
    myOutput.close(); 
    myInput.close(); 
} 
+0

謝謝,我會嘗試您的代碼 – NAZIK

1

它可能是由於以前存儲在你的Android設備版本的數據庫,請嘗試刪除從您的設備或代碼數據庫的變化版本,先前的DB使onupgrade將被稱爲

+0

我更改我的數據庫版本但不工作 – NAZIK