2014-02-18 73 views
0

我想要實現的基本想法是在SQlite數據庫中比較當前Android系統日期和現有日期。Android - SQLite比較數據庫中的日期到日期

的想法是1)如果數據庫不包含包含今天的日期條目,則允許新進入

2)如果數據庫已經包含今天的日期的條目,然後撤銷入境和輸出錯誤消息。

我將對DBAdapter目前擁有執行以下操作的方法:

public Cursor getDate(String date) { 
String where = KEY_DATE + "=" + date; 
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, 
       where, null, null, null, null, null); 
if (c !=null) { 
    c.moveToFirst(); 
} 
return c; 
} 

和我使用作出比較的方法是:

public void addRecord (View view){ 
    db.open(); 
    Cursor cursor = db.getDate(dateString); 

    if (cursor.moveToFirst()){ 
     AlertDialog.Builder builder = new AlertDialog.Builder(this); 
     builder.setTitle("Date"); 
     builder.setMessage("Entry for today exists, would you like to update this instead?"); builder.setPositiveButton("OK", null); 
     @SuppressWarnings("unused") 
     AlertDialog dialog = builder.show(); 
     db.close(); 
    } 
    else{ 

Do other work.. 

兩個日期的用於比較的格式使用此代碼:

long longDate = System.currentTimeMillis(); 
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); 
String dateString = sdf.format(longDate); 

其中我只是簡單地調用'dateString'

我的問題是它不執行正確的檢查並完全跳過我的else語句,即使我知道數據庫中存在一個「日期」。我的SQL語句正確嗎?

回答

0

嘗試建立查詢是這樣的:

db.query(true, DATABASE_TABLE, ALL_KEYS, KEY_DATE + "=?", new String[] {date}, null, null, null, null); 
+0

工作就像一個魅力!非常感謝! – user3197786

0

我用我的數據庫日期,但是我將它們保存爲與GETDATE()函數很值。 另外我發現問題取決於你使用的Date變量的類型。 我喜歡java.util.Date,永遠不會使用sql date變量。 我在哪裏做我的數據和所有比較的條件是getTime()這是一個Long值。 從數據庫中獲得的很長的值只需執行新的Date(longValue),並以這種方式獲得正確的日期變量。