Reputation: 5053
I am working with android device contacts. if android device contacts more than five thousand,Fetch data from contacts take too much time with blank screen. I have used bellow code to fetch data
private void fetchContacts1() {
String order = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC";
Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, order);
while (cursor.moveToNext()) {
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phonenumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
cursor.close();
}
I show all the contacts to recycle view.There are some devices which has more than ten thousand contacts. can you suggest me how to handle it.
Upvotes: 0
Views: 603
Reputation: 744
Use the Async task to load your contacts in the background. after loading for first-time store your list of contacts to your local database
below following links may help you
https://developer.android.com/guide/components/loaders
https://stackoverflow.com/a/40017905/10239870
class ContactLoader extends AsyncTask<Void, Void, List<Contact>> {
@Override
protected void onPreExecute() {
super.onPreExecute();
//visible your progress bar here
}
@Override
protected List<Contact> doInBackground(Void... voids) {
List<Contact> contacts = new ArrayList<>();
String order = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC";
Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, order);
while (cursor.moveToNext()) {
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phonenumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contacts.add(new Contact(name, phonenumber));
}
cursor.close();
return contacts;
}
@Override
protected void onPostExecute(List<Contact> contactList) {
super.onPostExecute(contactList);
//set list to your adapter
}
}
class Contact {
String name;
String number;
public Contact(String name, String number) {
this.name = name;
this.number = number;
}
public String getName() {
return name;
}
public String getNumber() {
return number;
}
public void setName(String name) {
this.name = name;
}
public void setNumber(String number) {
this.number = number;
}
}
Upvotes: 2