0

My app is always slow and sometimes crashes because to access to contacts list, I am using getContentResolver() which is making my app to run another additional process to main process. Whenever that additional process is running, my app starts to slow down and crashing.

So, is there any idea of accessing to contacts list without passing to that getContentResolver()?

Mugirase Emmanuel
  • 385
  • 1
  • 5
  • 14

2 Answers2

0

Use AsyncTaskLoader for fetching contact from device, it is recommended because it is asynchronous and also works well with activity lifecycle.

Amrat Singh
  • 331
  • 2
  • 13
0

You should use an AsynTask to do this work in background thread

private class LoadContacts extends AsyncTask<Void, Boolean, Boolean> {  
    protected void onPreExecute() {
        Log.e("LS", "Start !");
    }

    @Override
    protected Boolean doInBackground(Void... params) {
        ContentResolver cr = getContentResolver();
        Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        try {
            if (cur.getCount() > 0) {
                while (cur.moveToNext()) {
                    String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
                    String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

                    if (cur.getInt(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
                        Cursor pCur = cr.query(
                                ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                                null,
                                ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
                                new String[]{id},
                                null
                        );
                        while (pCur.moveToNext()) {
                            String phoneNo = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                            String data = "Name : " + name + " - Phone : " + phoneNo;
                        }
                        pCur.close();
                    }
                }
            }
            cur.close();
        } catch (NullPointerException | java.io.IOException e) {
            Log.e("LS", e.getMessage());
        }
        return true;
    }

    protected void onPostExecute(Boolean result) {
        Log.e("LS", "Done !");
    }
}
Arash Hatami
  • 5,297
  • 5
  • 39
  • 59
  • this level of nesting is not good. You should check inverting if statements/return early and delegating to methods – Tim Jun 15 '18 at 13:10