我有联系人应用程序,需要使用ContentObserver更新我的本地ORMLite数据库。我需要检查联系人更新。如果是,我需要更新联系人的姓名,如果它没有存储在我的本地数据库中。
我有两个项目 - CallItem(具有外部联系人字段)和ContactItem。
我的ContentObserver:
class CallsContentObserver extends ContentObserver {
Context _context;
Handler _handler;
public CallsContentObserver(Handler handler, Context context) {
super(handler);
this._context = context;
this._handler = handler;
}
@Override
public boolean deliverSelfNotifications() {
return true;
}
@Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
ArrayList<CallItem> contactsList = null;
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
Cursor contactLookupCursor = null;
try{
Dao<CallItem,Integer> daoSubject = db.getCallDao();
contactsList = (ArrayList<CallItem>) daoSubject.queryForAll();
for (CallItem contact : contactsList)
{
if (contact.getCall_contact() == null)
{
String contactNumber = Uri.encode(contact.getNumber());
String new_name = null;
contactLookupCursor =getContentResolver().query(
Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,contactNumber),
new String[] {PhoneLookup.DISPLAY_NAME, PhoneLookup._ID}, null, null, null);
while(contactLookupCursor.moveToNext()){
new_name = contactLookupCursor.getString(contactLookupCursor.getColumnIndexOrThrow(PhoneLookup.DISPLAY_NAME));
}
contactLookupCursor.close();
contact.setName(new_name);
daoSubject.update(contact);
}
}
}
catch(Exception e)
{e.printStackTrace();}
finally{db.close();}
}
}
所以我得到了所有的CallItems。然后我检查每个CallItem是否包含ContactItem,如果没有,我通过它的编号得到它的新名称,并用DAO用新值更新这个CallItem。但是这个解决方案很慢,我想让它更流畅。我怎样才能做到这一点?
答案 0 :(得分:0)
我找到了解决方法。 当用户第一次出现在应用程序中时,我不会解析所有通话记录。我只解析前20个电话,然后用onScroll下载更多。因此,名称继续进行并与本地数据库同步不会花费太多时间。
ORMLite非常好但是我觉得在这些情况下使用ContentResolver会更好。