I have read all the phone contacts from the device and set them to an adapter for the AutoCompleteTextView. The function that does this is:
private void storeContactsToArrayList() {
Log.d("In ", "storeContactsToArrayList() called");
List<Contact> contactList = new ArrayList<>();
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if ((cur != null ? cur.getCount() : 0) > 0) {
while (cur != null && 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));
// Log.i("GOT", "Name: " + name);
// Log.i("GOT", "Phone Number: " + phoneNo); //working
//To our POJO
Contact contact = new Contact();
contact.setName(name);
contact.setPhoneNumber(phoneNo);
contactList.add(contact);
}
pCur.close();
}
ArrayAdapter<Contact> contactsArrayAdapter =
new ArrayAdapter<Contact>(this, android.R.layout.simple_list_item_1, contactList);
//setting this adapter to our autocompleteTextView userInput
userInput.setAdapter(contactsArrayAdapter);
}
}
if(cur!=null){
cur.close();
}
}
However when I ran the code, I realized that the function takes quite some time to execute, which seems poor.
From what I know I should be using an inner class like AdapterTask extends Async Task
to do the same thing but asynchronously without blocking my main UI thread. I tried doing so, but I could not.
Please suggest me if there are any other ways of doing the same thing wihtout using AsyncTask, or if AsyncTask is the way to go, how can I achieve the thing that the above function is doing using AsyncTask.
Thanks.