2011-11-04 133 views
8

在Android中,我使用以下方法來查看sqlite數據庫是否存在,以及是否可以打開並使用它。在Android中,檢查sqlite數據庫是否存在失敗

如果測試失敗,我從資產中複製數據庫文件(這應該只發生一次,當用戶第一次啓動應用程序時)。

/* 
* Check if the database already exist to avoid re-copying the file each time you open the application. 
* @return true if it exists, false if it doesn't 
*/ 
private boolean checkDataBase() { 
    SQLiteDatabase checkDB = null; 

    try { 
     String myPath = DB_PATH + DB_NAME; 
     checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY); 
    } catch(SQLiteException e) { 
     //database does't exist yet. 
    } 

    if(checkDB != null){ 
     checkDB.close(); 
    } 
    return checkDB != null ? true : false; 
} 

的問題是,我收到來自用戶的報告說他們的數據已經被消滅和調查時,我可以看到數據庫被替換爲資產的數據庫。因此,即使用戶已有數據庫文件,但由於某些原因,SQLiteDatabase.openDatabase()有時會引發錯誤。我自己無法重現此問題,但似乎發生在某些用戶身上。

任何人都有一個想法可能是什麼問題在這裏?有沒有更好的方法來做這個測試?

+0

請與本http://stackoverflow.com/questions/20728808/android-reading-stored-sqlite-database – gandharv09

回答

32

如何檢查文件系統以查看數據庫是否存在,而不是先嚐試打開它?

你可能試圖打開一個已經打開的數據庫,這會導致你認爲它不存在的錯誤。

File database=getApplicationContext().getDatabasePath("databasename.db"); 

if (!database.exists()) { 
    // Database does not exist so copy it from assets here 
    Log.i("Database", "Not Found"); 
} else { 
    Log.i("Database", "Found"); 
} 
+0

這不會對我的工作幫助!見http://stackoverflow.com/questions/18391820/checking-if-database-exists –

+3

我只是想聯繫OP,以便他可以幫助我。我確實發佈了我自己的問題,上面給出了鏈接。我不是在「污染」任何東西,而只是尋求本網站的目的。 –

2

我想分享一個方法來檢查數據庫是否存在: 給我一個+1,如果它運行正常了你, 感謝。

private boolean checkDataBase() { 

    SQLiteDatabase checkDB = null; 

    try { 

     File database=myContext.getDatabasePath(DB_NAME); 

     if (database.exists()) { 

      Log.i("Database", "Found"); 

      String myPath = database.getAbsolutePath(); 

      Log.i("Database Path", myPath); 

      checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY); 

     } else {     

      // Database does not exist so copy it from assets here 
      Log.i("Database", "Not Found"); 

     } 

    } catch(SQLiteException e) { 

     Log.i("Database", "Not Found"); 

    } finally { 

     if(checkDB != null) { 

      checkDB.close(); 

     } 

    } 

    return checkDB != null ? true : false; 
} 
+0

不是一個好的方法,因爲它遭遇OP遇到的相同問題。如果數據庫存在但無法打開,則報告它不存在。如果您需要同時執行這兩項操作,那麼檢查數據庫是否存在以及是否可以打開應該是獨立的操作。此外,這依賴於拋出異常來確定數據庫狀態,這不是一種好的做法。 – Kuffs

相關問題