Two databases comparing data on the fly...Implementation advice needed
So I am looking to compare two databases, one that is read-only, and another that will update itself by adding what the read-only has, and deleting what the read-only database doesn't have. Essentially a sync of data.
At this point I have two cursors containing the data(one of which I converted to arraylist), and one field in each that's used to compare the keys. Here is the sample. I feel like I should be searching the opposite, as in searching through the read-only rather than looping through the read-only and searching each item in the arraylist. I wish there was some form or cursor comparing to make this faster and more reliable. Any ideas or suggestions?
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
开发者_如何学JAVA delImages(addImg);
}
It depends on the order of the image index you are keeping in each database.
The best situation would be if you are keeping them in some kind of numeric or lexicographic order. Then a simple O(N) merge algorithm would do the job.
Are you keeping them in the same order, but not lexicographic? Then you could use a diff-style algorithm to see which images need to be preserved, deleted, or added.
If you're not keeping them indexed in any order, then you're pretty much stuck with the O(N^2) or O(NlogN) approach.
精彩评论