Last active
July 16, 2019 09:57
-
-
Save shriomtri/5e489f744d90958c925c3908b98329c3 to your computer and use it in GitHub Desktop.
This helper class allow to fetch the list of all contact in android phone. It allow user to searh list of contact from name (query) as input.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.beatme.app.util; | |
import android.content.Context; | |
import android.database.Cursor; | |
import android.provider.ContactsContract; | |
import com.beatme.app.service.model.ContactModel; | |
import java.util.ArrayList; | |
import java.util.List; | |
public final class ContactHelper { | |
private static List<ContactModel> contactList = new ArrayList<>(); | |
//If no query is provided, all the contacts will be fetched | |
public static List<ContactModel> readContacts(Context context, String query) { | |
contactList.clear(); | |
String[] projection = {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Email.ADDRESS}; | |
Cursor cursor; | |
if (query == null || query.equals("")) { | |
cursor = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC "); | |
} else { | |
String[] mQuery = {"%"+ query + "%"}; | |
cursor = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, ContactsContract.Contacts.DISPLAY_NAME + " LIKE ? OR " + ContactsContract.CommonDataKinds.Phone.NUMBER + " LIKE ? ", mQuery, ContactsContract.Contacts.DISPLAY_NAME + " ASC "); | |
} | |
if (cursor != null && cursor.getCount() > 0) { | |
while (cursor.moveToNext()) { | |
String name = cursor.getString(0); | |
String phone = cursor.getString(1); | |
String email = cursor.getString(2); | |
if (!(phone == null || phone.equals(""))) { | |
contactList.add(new ContactModel(name,email,phone)); | |
} | |
} | |
cursor.close(); | |
} | |
return contactList; | |
} | |
public static String formatPhone(String phone){ | |
phone = phone.replaceAll("\\s",""); | |
if(phone.length()==10){ | |
phone = "+91"+phone; | |
}else if(phone.length()==11){ | |
phone = "+91"+phone.substring(1); | |
} | |
return phone; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment