0

我有联系人应用程序,需要使用 ContentObserver 更新我的本地 ORMLite 数据库。我需要查看联系人更新。如果是,我需要更新联系人的姓名,如果它没有存储在我的本地数据库中。

我有两个项目 - CallItem(具有外部联系人字段)和 ContactItem。

我的内容观察者:

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。但是这个解决方案很慢,我想让它更流畅。我怎样才能做到这一点?

4

1 回答 1

0

我找到了解决方案。当用户首次出现在应用程序中时,我不会解析所有通话记录。我只解析前 20 个调用,然后使用 onScroll 下载更多。因此,与本地数据库进行名称同步和同步不会花费太多时间。

ORMLite 非常好,不过我觉得在这些情况下使用 ContentResolver 会更好。

于 2013-12-19T10:54:18.640 回答