2011-09-10 16 views
0

所以我期待比較兩個數據庫,一個是隻讀的,另一個是通過添加只讀來更新自身,並刪除什麼只讀數據庫沒有。基本上是數據同步。兩個數據庫在實時比較數據......需要實現建議

在這一點上,我有兩個遊標包含數據(其中之一我轉換爲arraylist),並在每個用於比較鍵的字段。這是示例。我覺得我應該搜索相反的東西,例如搜索只讀而不是遍歷只讀和搜索數組列表中的每個項目。我希望有一些形式或光標比較,使之更快,更可靠。任何想法或建議?

ArrayList<String> addImg = new ArrayList<String>(); 
ArrayList<String> delImg = new ArrayList<String>(); 
image_store = m_db.getAllImages(); 
// this returns an arraylist of strings(can also change to return a cursor) 
local_images = img_db.getAllImages(); 

image_store.moveToFirst(); 
while(!image_store.isAfterLast()) { 
    key = image_store.getString(image_store.getColumnIndexOrThrow("name")); 
    // check if stored locally, if not add it to array. 
    if(Arrays.binarySearch(local_images, key) == -1) { 
     addImg.add(image_store.getString(image_store.getColumnIndexOrThrow("name"))); 
    } else { 
     delImg.add(key); 
    } 
    image_store.moveToNext(); 
} 
if(!addImg.isEmpty()) { 
    // this will loop through and delete from a cursor generated on another query 
    addImages(addImg); 
} 
if(!delImg.isEmpty()) { 
    // this will loop through and delete from a cursor generated on another query 
    delImages(addImg); 
} 

回答

0

它取決於您在每個數據庫中保留的圖像索引的順序。

最好的情況是,如果你讓他們在某種數字或字典順序。然後一個簡單的O(N)合併算法就可以完成這項工作。

你是否保持它們的順序相同,但不是詞典? 然後,您可以使用diff風格的算法來查看哪些圖像需要保留,刪除或添加。

如果你沒有以任何順序對它們進行索引,那麼你幾乎堅持O(N^2)或O(NlogN)方法。

+0

感謝您的建議。我確信每個專欄都有不確定性。我更關心這個問題與android特定的遊標,什麼是最好的方式來實現這一點。我已經有一個工作解決方案,但它需要維護多個臨時陣列。 – Du3