Search code examples
androidperformanceandroid-5.0-lollipop

Correct place to fetch contact details : android5


I am able to fetch contact details

Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext())
{
    String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
    String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
    Toast.makeText(getApplicationContext(), name, Toast.LENGTH_LONG).show();
    Log.d(name, phoneNumber);
}

What I want to know is where should I write this code?
I have written it in MainActivity (onCreate) function, but this leads to fetching contact everytime I open app, which is making app slow in loading.
I want to fetch contact details only installation time (so that it will be one time activity) and later on I need only newly added contact detail rather then getting whole list of contact.
Something like when a new contact is added, System Broadcaster broadcast newly added contact detail to all apps having permission of "android.permission.READ_CONTACTS" and then listener in my app fetch this data.
I am new in android so not able to use correct terminology.


Solution

  • You have to run it in separate thread using AsyncTask like this:

    public class ContactLoader extends AsyncTask<Void, Void, Cursor> {
    
    Context context;
    
    public ContactLoader(Context context){
      this.context= context;
    }
    @Override
    protected Cursor doInBackground(Void... voids) {
    
        return context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
    }
    
    @Override
    protected void onPostExecute(Cursor phones) {
        while (phones.moveToNext()) {
            String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            Toast.makeText(context, name, Toast.LENGTH_LONG).show();
            Log.d(name, phoneNumber);
        }
    
    }}
    

    and in your activity use it like this

    new ContactLoader(getApplicationContext()).execute();