Search code examples
androiddatabasecontactsandroid-contentprovider

Android: Quickly look up a list of contacts


I am currently developing an App which needs to look up a number of contacts (name and photo) via their phone number. However, this takes several seconds (For each contact: Look up the contact via their phone number, get contact's name & photo).

What would be a good strategy to speed this process up? I realize that I could use my own sqlite db which contains a list of exactly those names and photos I need. With such a database I could only do one query, then get the data for all contacts I need at once. This however would add quite some overhead I am hoping to avoid.

Is there a better (speak: simpler) solution?

Thank you.


Solution

  • you can use CursorAdapter and override bindView() method for example:

    @Override
    public void bindView(final View view, Context context, final Cursor cursor) {
        holder = (ItemHolder) view.getTag();
        ImageView icon = holder.getImageView();
        TextView name = holder.getName();
        final TextView email = holder.getEmail();
        icon.setBackgroundResource(R.drawable.contact_icon);
        name.setText(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
    
    
        final int contactid = cursor.getInt(cursor.getColumnIndex("_id"));
        mHandler.post(new Runnable() {
    
            @Override
            public void run() {
                Cursor emailCursor = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, "contact_id=?", new String[]{String.valueOf(contactid)}, null);
                startManagingCursor(emailCursor);
    //          Log.i("cursor:", emailCursor.getCount()+"");
                if(emailCursor!=null){
    
                    if(emailCursor.getCount()==0){
                        email.setText("");
                    }else {
                        while(emailCursor.moveToNext()){
                            String emails = emailCursor.getString(emailCursor.getColumnIndex("data1"));
                            email.setText(emails);
                        }
                    }
    
                }
                emailCursor.close();
            }
        });
    

    you would use ContactsContract.CommonDataKinds.Phone.CONTENT_URI instead of ContactsContract.CommonDataKinds.Email.CONTENT_URI .