How can I get all the names of the contacts in my Android and put them into array of strings?
Try this too,
private void getContactList() {
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(TAG, "Name: " + name);
Log.i(TAG, "Phone Number: " + phoneNo);
}
pCur.close();
}
}
}
if(cur!=null){
cur.close();
}
}
If you need more reference means refer this link Read ContactList
Get contacts info , photo contacts , photo uri and convert to Class model
1). Sample for Class model :
public class ContactModel {
public String id;
public String name;
public String mobileNumber;
public Bitmap photo;
public Uri photoURI;
}
2). get Contacts and convert to Model
public List<ContactModel> getContacts(Context ctx) {
List<ContactModel> list = new ArrayList<>();
ContentResolver contentResolver = ctx.getContentResolver();
Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
if (cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
Cursor cursorInfo = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null);
InputStream inputStream = ContactsContract.Contacts.openContactPhotoInputStream(ctx.getContentResolver(),
ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, new Long(id)));
Uri person = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, new Long(id));
Uri pURI = Uri.withAppendedPath(person, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
Bitmap photo = null;
if (inputStream != null) {
photo = BitmapFactory.decodeStream(inputStream);
}
while (cursorInfo.moveToNext()) {
ContactModel info = new ContactModel();
info.id = id;
info.name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
info.mobileNumber = cursorInfo.getString(cursorInfo.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
info.photo = photo;
info.photoURI= pURI;
list.add(info);
}
cursorInfo.close();
}
}
cursor.close();
}
return list;
}
public class MyActivity extends Activity
implements LoaderManager.LoaderCallbacks<Cursor> {
private static final int CONTACTS_LOADER_ID = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Prepare the loader. Either re-connect with an existing one,
// or start a new one.
getLoaderManager().initLoader(CONTACTS_LOADER_ID,
null,
this);
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// This is called when a new Loader needs to be created.
if (id == CONTACTS_LOADER_ID) {
return contactsLoader();
}
return null;
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
//The framework will take care of closing the
// old cursor once we return.
List<String> contacts = contactsFromCursor(cursor);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
// This is called when the last Cursor provided to onLoadFinished()
// above is about to be closed. We need to make sure we are no
// longer using it.
}
private Loader<Cursor> contactsLoader() {
Uri contactsUri = ContactsContract.Contacts.CONTENT_URI; // The content URI of the phone contacts
String[] projection = { // The columns to return for each row
ContactsContract.Contacts.DISPLAY_NAME
} ;
String selection = null; //Selection criteria
String[] selectionArgs = {}; //Selection criteria
String sortOrder = null; //The sort order for the returned rows
return new CursorLoader(
getApplicationContext(),
contactsUri,
projection,
selection,
selectionArgs,
sortOrder);
}
private List<String> contactsFromCursor(Cursor cursor) {
List<String> contacts = new ArrayList<String>();
if (cursor.getCount() > 0) {
cursor.moveToFirst();
do {
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
contacts.add(name);
} while (cursor.moveToNext());
}
return contacts;
}
}
and do not forget
<uses-permission android:name="android.permission.READ_CONTACTS" />
Get all contacts in less than a second and without any load in your activity.
Follow my steps works like a charm.
ArrayList<Contact> contactList = new ArrayList<>();
private static final String[] PROJECTION = new String[]{
ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER
};
private void getContactList() {
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PROJECTION, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
if (cursor != null) {
HashSet<String> mobileNoSet = new HashSet<String>();
try {
final int nameIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
final int numberIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
String name, number;
while (cursor.moveToNext()) {
name = cursor.getString(nameIndex);
number = cursor.getString(numberIndex);
number = number.replace(" ", "");
if (!mobileNoSet.contains(number)) {
contactList.add(new Contact(name, number));
mobileNoSet.add(number);
Log.d("hvy", "onCreaterrView Phone Number: name = " + name
+ " No = " + number);
}
}
} finally {
cursor.close();
}
}
}
Contacts
public class Contact {
public String name;
public String phoneNumber;
public Contact() {
}
public Contact(String name, String phoneNumber ) {
this.name = name;
this.phoneNumber = phoneNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
}
Benefits
less than a second
without load
ascending order
without duplicate contacts
Improving on the answer of #Adiii - It Will Cleanup The Phone Number and Remove All Duplicates
Declare a Global Variable
// Hash Maps
Map<String, String> namePhoneMap = new HashMap<String, String>();
Then Use The Function Below
private void getPhoneNumbers() {
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
// Loop Through All The Numbers
while (phones.moveToNext()) {
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
// Cleanup the phone number
phoneNumber = phoneNumber.replaceAll("[()\\s-]+", "");
// Enter Into Hash Map
namePhoneMap.put(phoneNumber, name);
}
// Get The Contents of Hash Map in Log
for (Map.Entry<String, String> entry : namePhoneMap.entrySet()) {
String key = entry.getKey();
Log.d(TAG, "Phone :" + key);
String value = entry.getValue();
Log.d(TAG, "Name :" + value);
}
phones.close();
}
Remember in the above example the key is phone number and value is a name so read your contents like 998xxxxx282->Mahatma Gandhi instead of Mahatma Gandhi->998xxxxx282
Cursor contacts = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
String aNameFromContacts[] = new String[contacts.getCount()];
String aNumberFromContacts[] = new String[contacts.getCount()];
int i = 0;
int nameFieldColumnIndex = contacts.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
int numberFieldColumnIndex = contacts.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
while(contacts.moveToNext()) {
String contactName = contacts.getString(nameFieldColumnIndex);
aNameFromContacts[i] = contactName ;
String number = contacts.getString(numberFieldColumnIndex);
aNumberFromContacts[i] = number ;
i++;
}
contacts.close();
The result will be aNameFromContacts array full of contacts. Also ensure that you have added
<uses-permission android:name="android.permission.READ_CONTACTS" />
in main.xml
This is the Method to get contact list Name and Number
private void getAllContacts() {
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Cursor phoneCursor = contentResolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id},
null);
if (phoneCursor != null) {
if (phoneCursor.moveToNext()) {
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
//At here You can add phoneNUmber and Name to you listView ,ModelClass,Recyclerview
phoneCursor.close();
}
}
}
}
}
}
//GET CONTACTLIST WITH ALL FIELD...
public ArrayList < ContactItem > getReadContacts() {
ArrayList < ContactItem > contactList = new ArrayList < > ();
ContentResolver cr = getContentResolver();
Cursor mainCursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if (mainCursor != null) {
while (mainCursor.moveToNext()) {
ContactItem contactItem = new ContactItem();
String id = mainCursor.getString(mainCursor.getColumnIndex(ContactsContract.Contacts._ID));
String displayName = mainCursor.getString(mainCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.parseLong(id));
Uri displayPhotoUri = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.DISPLAY_PHOTO);
//ADD NAME AND CONTACT PHOTO DATA...
contactItem.setDisplayName(displayName);
contactItem.setPhotoUrl(displayPhotoUri.toString());
if (Integer.parseInt(mainCursor.getString(mainCursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
//ADD PHONE DATA...
ArrayList < PhoneContact > arrayListPhone = new ArrayList < > ();
Cursor phoneCursor = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] {
id
}, null);
if (phoneCursor != null) {
while (phoneCursor.moveToNext()) {
PhoneContact phoneContact = new PhoneContact();
String phone = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
phoneContact.setPhone(phone);
arrayListPhone.add(phoneContact);
}
}
if (phoneCursor != null) {
phoneCursor.close();
}
contactItem.setArrayListPhone(arrayListPhone);
//ADD E-MAIL DATA...
ArrayList < EmailContact > arrayListEmail = new ArrayList < > ();
Cursor emailCursor = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", new String[] {
id
}, null);
if (emailCursor != null) {
while (emailCursor.moveToNext()) {
EmailContact emailContact = new EmailContact();
String email = emailCursor.getString(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
emailContact.setEmail(email);
arrayListEmail.add(emailContact);
}
}
if (emailCursor != null) {
emailCursor.close();
}
contactItem.setArrayListEmail(arrayListEmail);
//ADD ADDRESS DATA...
ArrayList < PostalAddress > arrayListAddress = new ArrayList < > ();
Cursor addrCursor = getContentResolver().query(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI, null, ContactsContract.CommonDataKinds.StructuredPostal.CONTACT_ID + " = ?", new String[] {
id
}, null);
if (addrCursor != null) {
while (addrCursor.moveToNext()) {
PostalAddress postalAddress = new PostalAddress();
String city = addrCursor.getString(addrCursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
String state = addrCursor.getString(addrCursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
String country = addrCursor.getString(addrCursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));
postalAddress.setCity(city);
postalAddress.setState(state);
postalAddress.setCountry(country);
arrayListAddress.add(postalAddress);
}
}
if (addrCursor != null) {
addrCursor.close();
}
contactItem.setArrayListAddress(arrayListAddress);
}
contactList.add(contactItem);
}
}
if (mainCursor != null) {
mainCursor.close();
}
return contactList;
}
//MODEL...
public class ContactItem {
private String displayName;
private String photoUrl;
private ArrayList<PhoneContact> arrayListPhone = new ArrayList<>();
private ArrayList<EmailContact> arrayListEmail = new ArrayList<>();
private ArrayList<PostalAddress> arrayListAddress = new ArrayList<>();
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getPhotoUrl() {
return photoUrl;
}
public void setPhotoUrl(String photoUrl) {
this.photoUrl = photoUrl;
}
public ArrayList<PhoneContact> getArrayListPhone() {
return arrayListPhone;
}
public void setArrayListPhone(ArrayList<PhoneContact> arrayListPhone) {
this.arrayListPhone = arrayListPhone;
}
public ArrayList<EmailContact> getArrayListEmail() {
return arrayListEmail;
}
public void setArrayListEmail(ArrayList<EmailContact> arrayListEmail) {
this.arrayListEmail = arrayListEmail;
}
public ArrayList<PostalAddress> getArrayListAddress() {
return arrayListAddress;
}
public void setArrayListAddress(ArrayList<PostalAddress> arrayListAddress) {
this.arrayListAddress = arrayListAddress;
}
}
public class EmailContact
{
private String email = "";
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
public class PhoneContact
{
private String phone="";
public String getPhone()
{
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
public class PostalAddress
{
private String city="";
private String state="";
private String country="";
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
//In Kotlin
private fun showContacts() {
// Check the SDK version and whether the permission is already granted or not.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(
requireContext(),
Manifest.permission.READ_CONTACTS
) != PackageManager.PERMISSION_GRANTED
) {
requestPermissions(
arrayOf(Manifest.permission.READ_CONTACTS),
1001
)
//After this point you wait for callback in onRequestPermissionsResult(int, String[], int[]) overriden method
} else {
// Android version is lesser than 6.0 or the permission is already granted.
getContactList()
}
}
private fun getContactList() {
val cr: ContentResolver = requireActivity().contentResolver
val cur: Cursor? = cr.query(
ContactsContract.Contacts.CONTENT_URI,
null, null, null, null
)
if ((if (cur != null) cur.getCount() else 0) > 0) {
while (cur != null && cur.moveToNext()) {
val id: String = cur.getString(
cur.getColumnIndex(ContactsContract.Contacts._ID)
)
val name: String = cur.getString(
cur.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME
)
)
if (cur.getInt(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
val pCur: Cursor? = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
arrayOf(id),
null
)
pCur?.let {
while (pCur.moveToNext()) {
val phoneNo: String = pCur.getString(
pCur.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER
)
)
Timber.i("Name: $name")
Timber.i("Phone Number: $phoneNo")
}
pCur.close()
}
}
}
}
if (cur != null) {
cur.close()
}
}
I am using this method, and it is working perfectly.
It gets fav, picture, name, number etc. (All the details of the contact). And also it is not repetitive.
List
private static List<FavContact> contactList = new ArrayList<>();
Method to get contacts
#SuppressLint("Range")
public static void readContacts(Context context) {
if (context == null)
return;
ContentResolver contentResolver = context.getContentResolver();
if (contentResolver == null)
return;
String[] fieldListProjection = {
ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER,
ContactsContract.Contacts.HAS_PHONE_NUMBER,
ContactsContract.Contacts.PHOTO_URI
,ContactsContract.Contacts.STARRED
};
String sort = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY + " ASC";
Cursor phones = contentResolver
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI
, fieldListProjection, null, null, sort);
HashSet<String> normalizedNumbersAlreadyFound = new HashSet<>();
if (phones != null && phones.getCount() > 0) {
while (phones.moveToNext()) {
String normalizedNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
if (Integer.parseInt(phones.getString(phones.getColumnIndex(
ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
if (normalizedNumbersAlreadyFound.add(normalizedNumber)) {
int id = phones.getInt(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
int fav = phones.getInt(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.STARRED));
boolean isFav;
isFav= fav == 1;
String uri = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
if(uri!=null){
contactList.add(new FavContact(id,isFav,uri,name,phoneNumber));
}
else{
contactList.add(new FavContact(id,isFav,name,phoneNumber));
}
}
}
}
phones.close();
}
}
Model Class
public class FavContact{
private int id;
private boolean isFavorite;
private String image;
private String name;
private String number;
public FavContact(int id,boolean isFavorite, String image, String name, String number){
this.id=id;
this.isFavorite = isFavorite;
this.image = image;
this.name = name;
this.number = number;
}
public FavContact(int id,boolean isFavorite, String name, String number){
this.id=id;
this.isFavorite = isFavorite;
this.name = name;
this.number = number;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public boolean isFavorite() {
return isFavorite;
}
public void setFavorite(boolean favorite) {
isFavorite = favorite;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
}
Adapter
public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.MyViewHolder> implements Filterable {
private final Context context;
private final List<FavContact> contactList;
private final List<FavContact> filterList;
private final OnMyOwnClickListener onMyOwnClickListener;
private final FavContactRepo favContactRepo;
public ContactAdapter(Application application,Context context, List<FavContact> contactList, OnMyOwnClickListener onMyOwnClickListener) {
this.context = context;
this.contactList = contactList;
this.onMyOwnClickListener = onMyOwnClickListener;
filterList = new ArrayList<>(contactList);
favContactRepo = new FavContactRepo(application);
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
final LayoutInflater inflater = LayoutInflater.from(context);
#SuppressLint("InflateParams") final View view = inflater.inflate(R.layout.design_fav_contact, null, false);
return new MyViewHolder(view,onMyOwnClickListener);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
final FavContact obj = contactList.get(position);
holder.tv_contact_name.setText(obj.getName());
holder.tv_contact_number.setText(obj.getNumber());
if(obj.getImage()==null){
Picasso.get().load(R.drawable.ic_circle_fav_no_dp).fit().into(holder.img_contact);
}
else{
Bitmap bp;
try {
bp = MediaStore.Images.Media
.getBitmap(context.getContentResolver(),
Uri.parse(obj.getImage()));
Glide.with(context).load(bp).centerInside().into(holder.img_contact);
} catch (IOException e) {
e.printStackTrace();
Picasso.get().load(R.drawable.ic_circle_fav_no_dp).fit().into(holder.img_contact);
}
}
obj.setFavorite(favContactRepo.checkIfFavourite(obj.getId()));
if(obj.isFavorite()){
Picasso.get().load(R.drawable.ic_menu_favorite_true).into(holder.img_fav_true_or_not);
}
else{
Picasso.get().load(R.drawable.ic_menu_favorite_false).into(holder.img_fav_true_or_not);
}
}
#Override
public int getItemCount() {
return contactList.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
static class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
CircleImageView img_contact;
TextView tv_contact_name,tv_contact_number;
ImageView img_fav_true_or_not;
ImageView img_call;
RecyclerView fav_contact_rv;
OnMyOwnClickListener onMyOwnClickListener;
public MyViewHolder(#NonNull View itemView, OnMyOwnClickListener onMyOwnClickListener) {
super(itemView);
img_contact = itemView.findViewById(R.id.img_contact);
tv_contact_name = itemView.findViewById(R.id.tv_contact_name);
img_fav_true_or_not = itemView.findViewById(R.id.img_fav_true_or_not);
tv_contact_number = itemView.findViewById(R.id.tv_contact_number);
img_call = itemView.findViewById(R.id.img_call);
fav_contact_rv = itemView.findViewById(R.id.fav_contact_rv);
this.onMyOwnClickListener = onMyOwnClickListener;
img_call.setOnClickListener(this);
img_fav_true_or_not.setOnClickListener(this);
img_contact.setOnClickListener(this);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
onMyOwnClickListener.onMyOwnClick(getAbsoluteAdapterPosition(),view);
}
}
public interface OnMyOwnClickListener{
void onMyOwnClick(int position,View view);
}
#Override
public Filter getFilter() {
return filteredList;
}
public Filter filteredList = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
List<FavContact> filteredList = new ArrayList<>();
if (constraint == null || constraint.length() == 0) {
filteredList=filterList;
} else {
String filterText = constraint.toString().toLowerCase().trim();
for (FavContact item : filterList) {
if (item.getName().toLowerCase().contains(filterText)
||item.getNumber().toLowerCase().contains(filterText)) {
filteredList.add(item);
}
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
#SuppressLint("NotifyDataSetChanged")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
contactList.clear();
contactList.addAll((ArrayList)results.values);
notifyDataSetChanged();
}
};
Related
In my android app i am trying to getting contacts list from my phonebook there is 1000 contacts app is taking to much time to load contacts and also it crashes here is my code
when contacts is loading it not responding app is crashes
private ArrayList<AllInOnetItem> getContacts() {
String phoneNo = "";
ArrayList<AllInOnetItem> contacts = new ArrayList<>();
ContentResolver cr = getActivity().getContentResolver();
//ContentResolver cResolver=context.getContextResolver();
ContentProviderClient mCProviderClient = cr.acquireContentProviderClient(ContactsContract.Contacts.CONTENT_URI);
Cursor cur = null;
try {
cur = mCProviderClient.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
} catch (RemoteException e) {
e.printStackTrace();
}
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()) {
phoneNo = pCur.getString(pCur.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.i(TAG, "Name: " + name);
Log.i(TAG, "Phone Number: " + phoneNo);
}
pCur.close();
}
contacts.add(new AllInOnetItem(name, phoneNo));
}
sortlist(contacts);
if (contactAdapter != null) {
contactAdapter.notifyDataSetChanged();
}
}
if (cur != null) {
cur.close();
}
return contacts;
}
Try Below code:
List<ContactVO> contactVOList = new ArrayList();
private void getContacts() {
AsyncTaskRunner runner = new AsyncTaskRunner();
runner.execute();
}
private class AsyncTaskRunner extends AsyncTask<String, String, String> {
private String resp;
ProgressDialog progressDialog;
#Override
protected String doInBackground(String... params) {
ContactVO contactVO;
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
contactVO = new ContactVO();
contactVO.setContactName(name);
Cursor phoneCursor = contentResolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id},
null);
if (phoneCursor.moveToNext()) {
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contactVO.setContactNumber(phoneNumber);
}
phoneCursor.close();
Cursor emailCursor = contentResolver.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{id}, null);
while (emailCursor.moveToNext()) {
String emailId = emailCursor.getString(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
}
contactVOList.add(contactVO);
}
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
// execution of result of Long time consuming operation
hideProgressBar();
setContactAdapter();
}
#Override
protected void onPreExecute() {
showProgressBar();
}
}
public class ContactVO {
private String ContactImage;
private String ContactName;
private String ContactNumber;
private boolean isChecked;
public String getContactImage() {
return ContactImage;
}
public void setContactImage(String contactImage) {
this.ContactImage = ContactImage;
}
public String getContactName() {
return ContactName;
}
public void setContactName(String contactName) {
ContactName = contactName;
}
public String getContactNumber() {
return ContactNumber;
}
public void setContactNumber(String contactNumber) {
ContactNumber = contactNumber;
}
public boolean isChecked() {
return isChecked;
}
public void setChecked(boolean checked) {
isChecked = checked;
}
#Override
public String toString() {
return ContactNumber.replace(" ","");
}
}
public class AllContactsAdapter extends RecyclerView.Adapter<AllContactsAdapter.ContactViewHolder> implements Filterable {
private List<ContactVO> contactVOList,contactListFiltered;
private Context mContext;
public AllContactsAdapter(List<ContactVO> contactVOList, Context mContext){
this.contactVOList = contactVOList;
this.contactListFiltered = contactVOList;
this.mContext = mContext;
}
#Override
public ContactViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.single_contact_view, null);
ContactViewHolder contactViewHolder = new ContactViewHolder(view);
return contactViewHolder;
}
#Override
public void onBindViewHolder(ContactViewHolder holder, int position) {
final ContactVO contactVO = contactListFiltered.get(position);
holder.tvContactName.setText(contactVO.getContactName());
holder.tvPhoneNumber.setText(contactVO.getContactNumber());
holder.cbContact.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
contactVO.setChecked(b);
}
});
if(contactVO.isChecked()){
holder.cbContact.setChecked(true);
}
else {
holder.cbContact.setChecked(false);
}
}
#Override
public int getItemCount() {
return contactListFiltered.size();
}
public List<ContactVO> getContacts(){
return contactVOList;
}
public List<ContactVO> getSelectedContacts(){
List<ContactVO> selectedContactVOList = new ArrayList<>();
for (int i = 0; i < contactVOList.size(); i++) {
if(contactVOList.get(i).isChecked()){
selectedContactVOList.add(contactVOList.get(i));
}
}
return selectedContactVOList;
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
if (charString.isEmpty()) {
contactListFiltered = contactVOList;
} else {
List<ContactVO> filteredList = new ArrayList<>();
for (ContactVO row : contactVOList) {
// name match condition. this might differ depending on your requirement
// here we are looking for name or phone number match
if (row.getContactName().toLowerCase().contains(charString.toLowerCase()) || row.getContactNumber().contains(charSequence)) {
filteredList.add(row);
}
}
contactListFiltered = filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = contactListFiltered;
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
contactListFiltered = (ArrayList<ContactVO>) filterResults.values;
notifyDataSetChanged();
}
};
}
public static class ContactViewHolder extends RecyclerView.ViewHolder{
ImageView ivContactImage;
TextView tvContactName;
TextView tvPhoneNumber;
CheckBox cbContact;
public ContactViewHolder(View itemView) {
super(itemView);
ivContactImage = (ImageView) itemView.findViewById(R.id.ivContactImage);
tvContactName = (TextView) itemView.findViewById(R.id.tvContactName);
tvPhoneNumber = (TextView) itemView.findViewById(R.id.tvPhoneNumber);
cbContact = itemView.findViewById(R.id.cbContact);
}
}
}
private void setContactAdapter() {
contactAdapter = new AllContactsAdapter(contactVOList, getApplicationContext());
rvContacts.setLayoutManager(new LinearLayoutManager(SendSMSActivity.this));
rvContacts.setAdapter(contactAdapter);
rlContacts.setVisibility(View.VISIBLE);
}
You can fetch your contacts in background thread. For background task you can use WorkManager, Firebase JobDispatcher, AsyncTask etc. If you will use AsyncTask then you have to keep in mind of memory leaking problem with context.
I am not able to find any appropriate solution for below issue. I have some method which return contact names and phone numbers from phone, and it works on lots of devices.
But, problem is this method does not work on my htc(android 4.3.1). I think, maybe main cause is on line of declaration of cursor(Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);), because I checked Cursor object by getCount method and it showed me a zero, which means it could not get any data. I tried many ways of declaring Cursor object, but I didn't succeed.
thanks in advance! Please check Code mentioned below:
private List<String> getContactNames() {
List<String> contacts = new ArrayList<>();
// Get the ContentResolver
ContentResolver cr = getContentResolver();
// Get the Cursor of all the contacts
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));
phoneNumber = phoneNumber.replaceAll("[()+]", "");
phoneNumber = phoneNumber.replaceAll(" ", "");
if (phoneNumber.startsWith("8")) {
phoneNumber = phoneNumber.replaceFirst("8", "7");
}
//contactNames.add(phoneNumber);
contacts.add(name + "&&" + phoneNumber);
}
phones.close();
Collections.sort(contacts, String.CASE_INSENSITIVE_ORDER);
List<String> contactList =
new ArrayList<>(new LinkedHashSet<String>(contacts));
for (int i = 0; i < contactList.size(); i++) {
String tem = contactList.get(i);
String[] arr = tem.split("&&");
contactNumbers.add(arr[1]);
contactNames.add(arr[0]);
}
//Toast.makeText(this, contactNames.toString(), Toast.LENGTH_LONG).show();
return contactList;
}
Use this.
public class ContactsProvider {
private Uri QUERY_URI = ContactsContract.Contacts.CONTENT_URI;
private String CONTACT_ID = ContactsContract.Contacts._ID;
private String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
private Uri EMAIL_CONTENT_URI = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
private String EMAIL_CONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
private String EMAIL_DATA = ContactsContract.CommonDataKinds.Email.DATA;
private String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
private String PHONE_NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
private Uri PHONE_CONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
private String PHONE_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
private String STARRED_CONTACT = ContactsContract.Contacts.STARRED;
private ContentResolver contentResolver;
public ContactsProvider() {
contentResolver = GenericApplication.getContext().getContentResolver();
}
public List<Contact> getContacts() {
List<Contact> contactList = new ArrayList<Contact>();
String[] projection = new String[]{CONTACT_ID, DISPLAY_NAME, HAS_PHONE_NUMBER, STARRED_CONTACT};
String selection = null;
Cursor cursor = contentResolver.query(QUERY_URI, projection, selection, null, null);
while (cursor.moveToNext()) {
Contact contact = getContact(cursor);
contactList.add(contact);
}
cursor.close();
return contactList;
}
private Contact getContact(Cursor cursor) {
String contactId = cursor.getString(cursor.getColumnIndex(CONTACT_ID));
String name = (cursor.getString(cursor.getColumnIndex(DISPLAY_NAME)));
Uri uri = Uri.withAppendedPath(QUERY_URI, String.valueOf(contactId));
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(uri);
String intentUriString = intent.toUri(0);
Contact contact = new Contact();
contact.id = Integer.valueOf(contactId);
contact.name = name;
contact.uriString = intentUriString;
getPhone(cursor, contactId, contact);
getEmail(contactId, contact);
return contact;
}
private void getEmail(String contactId, Contact contact) {
Cursor emailCursor = contentResolver.query(EMAIL_CONTENT_URI, null, EMAIL_CONTACT_ID + " = ?", new String[]{contactId}, null);
while (emailCursor.moveToNext()) {
String email = emailCursor.getString(emailCursor.getColumnIndex(EMAIL_DATA));
if (!TextUtils.isEmpty(email)) {
contact.email = email;
}
}
emailCursor.close();
}
private void getPhone(Cursor cursor, String contactId, Contact contact) {
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
Cursor phoneCursor = contentResolver.query(PHONE_CONTENT_URI, null, PHONE_CONTACT_ID + " = ?", new String[]{contactId}, null);
while (phoneCursor.moveToNext()) {
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(PHONE_NUMBER));
contact.phone = phoneNumber;
}
phoneCursor.close();
}
}
}
Use this method:
private void LoadContactsWithPhone() {
TextView contactView = (TextView) getView().findViewById(R.id.txtContacts);
contactView.setText("");
Cursor cursor = getContactsWithPhone();
while (cursor.moveToNext()) {
String displayName = cursor.getString(cursor
.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
String phoneNo = cursor.getString(cursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contactView.append("Name: ");
contactView.append(displayName);
contactView.append("\n");
contactView.append("Phone: ");
contactView.append(phoneNo);
contactView.append("\n\n");
}
}
private Cursor getContactsWithPhone() {
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String[] projection = new String[]{ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER
};
String selection = ContactsContract.Contacts.HAS_PHONE_NUMBER + " = ?";
String[] selectionArgs = new String[]{String.valueOf(1)};
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
return getActivity().getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
}
Sorry guys, main cause was the device itself, I checked other similar applications that use the device contacts as whatsapp, and these applications are also unable to use the phone's contacts. All answers are presented here work perfectly , as good as my method.
Please used the following code its working on my end on all devices:-
public ArrayList<Contact_Model> getContacts(){
ArrayList<Contact_Model> contact_models = new ArrayList<>();
// ContentResolver cr = context.getActivity().getContentResolver();
ContentProviderClient mCProviderClient = context.getActivity().getContentResolver().acquireContentProviderClient(ContactsContract.Contacts.CONTENT_URI);
Cursor cur = mCProviderClient.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
Contact_Model contact_model = new Contact_Model();
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String firstname;
String lastName = "";
if (name != null) {
contact_model.setContactId(id);
contact_model.setContactName(name);
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
// get the phone number
Cursor pCur = mCProviderClient.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
String phone = pCur.getString(
pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contact_model.setContactNumber(phone);
}
pCur.close();
// get email and type
Cursor emailCur = mCProviderClient.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{id}, null);
while (emailCur.moveToNext()) {
// This would allow you get several email addresses
// if the email addresses were stored in an array
String email = emailCur.getString(
emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
contact_model.setContactEmail(email);
}
emailCur.close();
Cursor photoCursor = mCProviderClient.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id}, null);
while (photoCursor.moveToNext()) {
String photo = photoCursor.getString(photoCursor.getColumnIndex(ContactsContract.Contacts.PHOTO_ID));
if (photo == null) {
contact_model.setContactPhoto("");
} else {
contact_model.setContactPhoto(photo);
}
}
contact_model.setContactOtherDetails("");
photoCursor.close();
// Get note.......
String noteWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] noteWhereParams = new String[]{id,
ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE};
Cursor noteCur = mCProviderClient.query(ContactsContract.Data.CONTENT_URI, null, noteWhere, noteWhereParams, null);
if (noteCur.moveToFirst()) {
String note = noteCur.getString(noteCur.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE));
System.out.println("Note " + note);
contact_model.setNote(note);
}
noteCur.close();
// Get Organizations.........
String orgWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] orgWhereParams = new String[]{id,
ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE};
Cursor orgCur = mCProviderClient.query(ContactsContract.Data.CONTENT_URI,
null, orgWhere, orgWhereParams, null);
if (orgCur.moveToFirst()) {
String orgName = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.DATA));
String title = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.TITLE));
if (orgName != null) {
contact_model.setOrganization(orgName);
}
if (title != null) {
contact_model.setJob(title);
}
}
orgCur.close();
}
contact_models.add(contact_model);
}
}
}
return contact_models;
}
Contact Model:-
public class Contact_Model implements Serializable {
private String contactId = "", contactName = "", contactNumber = "", contactEmail = "", contactPhoto = "", contactOtherDetails = "";
private String firstName = "", lastName = "", note = "", organization = "", job = "", dob = "";
ContactAccount contactAccount;
public Contact_Model() {
}
public Contact_Model(String contactId, String contactName, String contactNumber, String contactEmail, String contactPhoto, String contactOtherDetails, String firstName, String lastName,
String note, String organization, String job, String dob) {
this.contactId = contactId;
this.contactName = contactName;
this.contactNumber = contactNumber;
this.contactEmail = contactEmail;
this.contactPhoto = contactPhoto;
this.contactOtherDetails = contactOtherDetails;
this.firstName = firstName;
this.lastName = lastName;
this.note = note;
this.organization = organization;
this.dob = dob;
this.job = job;
}
public ContactAccount getContactAccount() {
return contactAccount;
}
public void setContactAccount(ContactAccount contactAccount) {
this.contactAccount = contactAccount;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public String getOrganization() {
return organization;
}
public void setOrganization(String organization) {
this.organization = organization;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getContactId() {
return contactId;
}
public void setContactId(String contactId) {
this.contactId = contactId;
}
public String getContactName() {
return contactName;
}
public void setContactName(String contactName) {
this.contactName = contactName;
}
public String getContactNumber() {
return contactNumber;
}
public void setContactNumber(String contactNumber) {
this.contactNumber = contactNumber;
}
public String getContactEmail() {
return contactEmail;
}
public void setContactEmail(String contactEmail) {
this.contactEmail = contactEmail;
}
public String getContactPhoto() {
return contactPhoto;
}
public void setContactPhoto(String contactPhoto) {
this.contactPhoto = contactPhoto;
}
public String getContactOtherDetails() {
return contactOtherDetails;
}
public void setContactOtherDetails(String contactOtherDetails) {
this.contactOtherDetails = contactOtherDetails;
}
}
ContactAccount.class
public class ContactAccount implements Serializable {
String accountName = "", accountType = "";
public ContactAccount(){
}
public ContactAccount(String accountName, String accountType) {
this.accountName = accountName;
this.accountType = accountType;
}
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public String getAccountType() {
return accountType;
}
public void setAccountType(String accountType) {
this.accountType = accountType;
}
}
Hope this helps you..
In my android code
I want to fetch contact's name,email and phone number as as json and then want to display.
Here is my code:
public class MainActivity extends Activity {
public TextView outputText;
String[] phoneNumber;
String[] email;
String name;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
outputText = (TextView) findViewById(R.id.textView1);
try {
//fetchContacts();
outputText.setText(fetchContacts());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String fetchContacts() throws JSONException {
Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
String _ID = ContactsContract.Contacts._ID;
String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
Uri EmailCONTENT_URI = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
String EmailCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
String DATA = ContactsContract.CommonDataKinds.Email.DATA;
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(CONTENT_URI, null, null, null,
null);
List<Contact> contacts = new ArrayList<Contact>();
Gson gson = new Gson();
// Loop for every contact in the phone
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String contact_id = cursor
.getString(cursor.getColumnIndex(_ID));
name = cursor.getString(cursor.getColumnIndex(DISPLAY_NAME));
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor
.getColumnIndex(HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
int p = 0;
// Query and loop for every phone number of the contact
Cursor phoneCursor = contentResolver.query(
PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?",
new String[] { contact_id }, null);
while (phoneCursor.moveToNext()) {
phoneNumber[p] = phoneCursor.getString(phoneCursor
.getColumnIndex(NUMBER));
p++;
}
phoneCursor.close();
int q = 0;
// Query and loop for every email of the contact
Cursor emailCursor = contentResolver.query(
EmailCONTENT_URI, null, EmailCONTACT_ID + " = ?",
new String[] { contact_id }, null);
while (emailCursor.moveToNext()) {
email[q] = emailCursor.getString(emailCursor
.getColumnIndex(DATA));
q++;
}
emailCursor.close();
contacts.add(new Contact(name, phoneNumber, email));
}
}
}
return gson.toJson(contacts);
}
}
But I am getting nullpointer exception error :
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.contactdemo/com.example.contactdemo.MainActivity}: java.lang.NullPointerException
error found in below line of code:
phoneNumber[p] = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
Here I am storing phonenumber and email as array.Is there array initialization problem ?? any idea guys?
You can use these approach to finds the contact from contact list
class FetchDeviceContact extends AsyncTask<Void, Integer, String>
{
protected void onPreExecute (){
Constant.showProgressDialog(AddDeviceContactScreeen.this);
}
protected String doInBackground(Void...arg0) {
arrayList.clear();
ContentResolver cr = AddDeviceContactScreeen.this.getContentResolver();
Cursor cur = AddDeviceContactScreeen.this.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Data._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
String photoUri = cur.getString(cur.getColumnIndex(ContactsContract.Data.PHOTO_THUMBNAIL_URI));
Bitmap my_btmp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_arrow_up_blue);
String email = null;
String phoneNo = null;
Cursor phonecur = AddDeviceContactScreeen.this.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id}, null);
if (photoUri != null) {
Uri my_contact_Uri = Uri.parse(photoUri);
try {
my_btmp = MediaStore.Images.Media.getBitmap(AddDeviceContactScreeen.this.getContentResolver(), my_contact_Uri);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (phonecur.getCount() > 0) {
while (phonecur.moveToNext()) {
phoneNo = phonecur.getString(phonecur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
}
Cursor emailCur = cr.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{id}, null);
while (emailCur.moveToNext()) {
// to get the contact names
// = cur1.getString(cur1.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA)
email = emailCur.getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
if (email != null) {
System.out.println("Email============== :" + email);
}
}
emailCur.close();
ContactBean bean = new ContactBean();
bean.setName(name);
bean.setEmail(email);
bean.setImage(my_btmp);
bean.setPhone_number(phoneNo);
if (phoneNo == null || email == null) {
} else {
arrayList.add(bean);
}
}
return "";
}
protected void onProgressUpdate(Integer...a){
}
protected void onPostExecute(String result) {
Constant.cancelDialog();
}
}
new FetchDeviceContact().execute();
Create the getter and setter class for it:-
public class ContactBean {
String name;
String email;
Bitmap image;
String phone_number;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Bitmap getImage() {
return image;
}
public void setImage(Bitmap image) {
this.image = image;
}
public String getPhone_number() {
return phone_number;
}
public void setPhone_number(String phone_number) {
this.phone_number = phone_number;
}
}
I think you should fix :
if (phoneCursor.movetoFirst()){
while (!phoneCursor.isAfterLast()) {
phoneNumber[p] = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
p++;
phoneCursor.movetoNext();
}
}
Here:
phoneNumber[p] = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
NullPointerException caused because phoneNumber is null and not initialized.
Use Cursor. getCount() to initialize it as:
phoneNumber = new String[phoneCursor.getCount()];
phoneCursor.moveToFirst();
while (phoneCursor.moveToNext()) {
//..your code here..
}
Is it possible to write APN programmatically on Android 4.4?
I noticed that the Telephony.Carriers is available for API level 19.
I have a software with APN write feature. Since Android 4.0 you can write APN settings only if you have system permissions. My software was designed to be a system software, so I can write APN and other settings. But, this feature is no longer working in Android 4.4 and I don't know why yet.
After read the Telephony.Carriers class, I could not find a new way to write APN. It's just a class to tell you informations but can't change them.
My code to write APN is:
public class APN {
public static final int AUTH_TYPE_UNKNOW = -1;
public static final int AUTH_TYPE_NONE = 0;
public static final int AUTH_TYPE_PAP = 1;
public static final int AUTH_TYPE_CHAP = 2;
public static final int AUTH_TYPE_PAP_OR_CHAP = 3;
private int id;
private String name;
private String user;
private String password;
private String apn;
private String mcc;
private String mnc;
private String type;
private String server;
private String proxy;
private String port;
private String mmsProxy;
private String mmsPort;
private String mmsc;
private String current;
private int authType;
public APN() {
id = -1;
name = "";
user = "";
password = "";
apn = "";
mcc = "";
mnc = "";
type = "default,supl";
server = "";
proxy = "";
port = "";
mmsProxy = "";
mmsPort = "";
mmsc = "";
current = "";
authType = AUTH_TYPE_NONE;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getApn() {
return apn;
}
public void setApn(String apn) {
this.apn = apn;
}
public String getMcc() {
return mcc;
}
public void setMcc(String mcc) {
this.mcc = mcc;
}
public String getMnc() {
return mnc;
}
public void setMnc(String mnc) {
this.mnc = mnc;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getServer() {
return server;
}
public void setServer(String server) {
this.server = server;
}
public String getProxy() {
return proxy;
}
public void setProxy(String proxy) {
this.proxy = proxy;
}
public String getMmsProxy() {
return mmsProxy;
}
public void setMmsProxy(String mmsProxy) {
this.mmsProxy = mmsProxy;
}
public String getMmsPort() {
return mmsPort;
}
public void setMmsPort(String mmsPort) {
this.mmsPort = mmsPort;
}
public String getMmsc() {
return mmsc;
}
public void setMmsc(String mmsc) {
this.mmsc = mmsc;
}
public String getCurrent() {
return current;
}
public void setCurrent(String current) {
this.current = current;
}
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
public int getAuthType() {
return authType;
}
public void setAuthType(int authType) {
this.authType = authType;
}
}
and:
public class APNUtils {
private static final Uri APN_TABLE_URI = Uri.parse("content://telephony/carriers");
private static final Uri APN_PREFER_URI = Uri.parse("content://telephony/carriers/preferapn");
private static ContentValues prepareValues(APN apn) {
ContentValues values = new ContentValues();
if (!apn.getName().trim().equals(""))
values.put("name", apn.getName());
if (!apn.getApn().trim().equals(""))
values.put("apn", apn.getApn());
if (!apn.getMcc().trim().equals(""))
values.put("mcc", apn.getMcc());
if (!apn.getMnc().trim().equals(""))
values.put("mnc", apn.getMnc());
if (!apn.getMcc().trim().equals("") && !apn.getMnc().trim().equals(""))
values.put("numeric", apn.getMcc() + apn.getMnc());
if (!apn.getUser().trim().equals(""))
values.put("user", apn.getUser());
if (!apn.getPassword().trim().equals(""))
values.put("password", apn.getPassword());
if (!apn.getServer().trim().equals(""))
values.put("server", apn.getServer());
if (!apn.getProxy().trim().equals(""))
values.put("proxy", apn.getProxy());
if (!apn.getPort().trim().equals(""))
values.put("port", apn.getPort());
if (!apn.getMmsProxy().trim().equals(""))
values.put("mmsproxy", apn.getMmsProxy());
if (!apn.getMmsPort().trim().equals(""))
values.put("mmsport", apn.getMmsPort());
if (!apn.getMmsc().trim().equals(""))
values.put("mmsc", apn.getMmsc());
if (!apn.getType().trim().equals(""))
values.put("type", apn.getType());
if (!apn.getCurrent().trim().equals(""))
values.put("current", apn.getCurrent());
values.put("authtype", apn.getAuthType());
return values;
}
public static int createNewApn(Context context, APN apn, boolean setAsDefaultAPN) {
Logs.infoLog("APNutils.createNewApn.");
int apnid = -1;
try {
if (apn != null) {
Logs.infoLog("APNutils.createNewApn. Reading APN list.");
Uri APN_URI = Uri.parse("content://telephony/carriers");
ContentResolver resolver = context.getContentResolver();
Logs.infoLog("APNutils.createNewApn. Creating new registry based on parameters.");
ContentValues values = prepareValues(apn);
Logs.infoLog("APNutils.createNewApn. Inserting new APN.");
Cursor c = null;
Uri newRow = resolver.insert(APN_URI, values);
if(newRow != null) {
Logs.infoLog("APNutils.createNewApn. Getting new ID.");
c = resolver.query(newRow, null, null, null, null);
int tableIndex = c.getColumnIndex("_id");
c.moveToFirst();
apnid = c.getShort(tableIndex);
} else
Logs.warningLog("APNutils.createNewApn. New APN was not found. Inserting failed?");
if(c != null){
c.close();
}
if (apnid > -1 && setAsDefaultAPN) {
Logs.infoLog("APNutils.createNewApn. Setting new APN as default.");
ContentValues v = new ContentValues(1);
v.put("apn_id", apnid);
context.getContentResolver().update(APN_PREFER_URI, v, null, null);
}
} else
Logs.warningLog("APNutils.createNewApn. Invalid apn (null).");
} catch (Exception e) {
Logs.errorLog("createNewApn: error", e);
}
Logs.infoLog("APNutils.createNewApn. Returning ID " + String.valueOf(apnid));
return apnid;
}
public static boolean updateApn(Context context, int id, APN apn) {
Logs.infoLog("APNutils.updateApn.");
if (apn != null) {
try {
Logs.infoLog("APNutils.updateApn. Reading APN list.");
Uri APN_URI = Uri.parse("content://telephony/carriers");
ContentResolver resolver = context.getContentResolver();
Logs.infoLog("APNutils.updateApn. Creating new registry based on parameters.");
ContentValues values = prepareValues(apn);
Logs.infoLog("APNutils.updateApn. Inserting new APN.");
int result = resolver.update(APN_URI, values, "_id = " + String.valueOf(id), null);
if (result != -1) {
Logs.infoLog("APNutils.updateApn. APN updated.");
return true;
} else {
Logs.warningLog("APNutils.updateApn. Invalid ID (" + String.valueOf(id) + ").");
return false;
}
} catch (Exception e) {
Logs.errorLog("APNUtils.updateApn error: ", e);
return false;
}
} else {
Logs.warningLog("APNutils.updateApn. Invalid apn (null).");
return false;
}
}
public static boolean verifyApn(Context context, String apn) {
Logs.infoLog("APNutils.verifyApn.");
return getApn(context, apn) > -1;
}
public static int getApn(Context context, String apn) {
Logs.infoLog("APNutils.getApn.");
int result = -1;
Logs.infoLog("APNutils.getApn. Looking for APN " + apn);
String columns[] = new String[] { "_ID", "NAME" };
String where = "name = ?";
String wargs[] = new String[] { apn };
String sortOrder = null;
Cursor cur = context.getContentResolver().query(APN_TABLE_URI, columns, where, wargs, sortOrder);
if (cur != null) {
int tableIndex = cur.getColumnIndex("_id");
if (cur.moveToFirst()) {
Logs.infoLog("APNutils.getApn. APN found.");
result = cur.getShort(tableIndex);
}
cur.close();
}
if (result == -1)
Logs.warningLog("APNutils.getApn. APN not found.");
return result;
}
public static boolean setPreferredApn(Context context, String apn) {
Logs.infoLog("APNutils.setPreferredApn.");
boolean changed = false;
Logs.infoLog("APNutils.setPreferredApn. Looking for APN " + apn);
String columns[] = new String[] { "_ID", "NAME" };
String where = "name = ?";
String wargs[] = new String[] { apn };
String sortOrder = null;
Cursor cur = context.getContentResolver().query(APN_TABLE_URI, columns, where, wargs, sortOrder);
if (cur != null) {
if (cur.moveToFirst()) {
Logs.infoLog("APNutils.setPreferredApn. APN found. Setting as default.");
ContentValues values = new ContentValues(1);
values.put("apn_id", cur.getLong(0));
if (context.getContentResolver().update(APN_PREFER_URI, values, null, null) == 1) {
Logs.infoLog("APNutils.setPreferredApn. APN marked as default.");
changed = true;
}
}
cur.close();
}
if (!changed)
Logs.warningLog("APNutils.setPreferredApn. APN not found or could not be marked as default.");
return changed;
}
public static APN[] getAllApnList(Context context) {
Logs.infoLog("APNutils.getAllApnList.");
APN[] result = null;
Uri contentUri = Uri.parse("content://telephony/carriers/");
Cursor cursor = null;
try
{
cursor = context.getContentResolver().query(contentUri,
new String[] {"_ID", "name", "apn", "mcc", "mnc", "numeric", "user", "password", "server", "proxy",
"port", "mmsproxy", "mmsport", "mmsc", "type", "current", "authtype "}, null, null, null);
if (cursor != null)
{
result = new APN[cursor.getCount()];
int i = 0;
while (cursor.moveToNext())
{
APN apn = new APN();
apn.setId(cursor.getInt(0));
apn.setName(cursor.getString(1));
apn.setApn(cursor.getString(2));
apn.setMcc(cursor.getString(3));
apn.setMnc(cursor.getString(4));
apn.setUser(cursor.getString(6));
apn.setPassword(cursor.getString(7));
apn.setServer(cursor.getString(8));
apn.setProxy(cursor.getString(9));
apn.setPort(cursor.getString(10));
apn.setMmsProxy(cursor.getString(11));
apn.setMmsPort(cursor.getString(12));
apn.setMmsc(cursor.getString(13));
apn.setType(cursor.getString(14));
apn.setCurrent(cursor.getString(15));
apn.setAuthType(cursor.getInt(16));
result[i] = apn;
i++;
}
}
}
catch (Exception ex)
{
//Handle exceptions here
return null;
}
finally
{
if (cursor != null)
cursor.close();
}
return result;
}
}
i am trying to show contact number as well as contact names in a list view.
i have done...:
public String DisplayName(String number) {
Uri uri = Uri.withAppendedPath(
ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(number));
String name = "?";
ContentResolver contentResolver = getContentResolver();
Cursor contactLookup = contentResolver.query(uri, new String[] {
BaseColumns._ID, ContactsContract.PhoneLookup.DISPLAY_NAME },
null, null, null);
try {
if (contactLookup != null && contactLookup.getCount() > 0) {
contactLookup.moveToNext();
name = contactLookup.getString(contactLookup
.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
// String contactId =
// contactLookup.getString(contactLookup.getColumnIndex(BaseColumns._ID));
}
} finally {
if (contactLookup != null) {
contactLookup.close();
}
}
return name;
}
but my app keep on force closing , i dont know why?? i have include the permission also...
""
any guess? why
use this 2 methods:
/*
* Returns contact's id
*/
private String getContactId(String phoneNumber, Context context) {
ContentResolver mResolver = context.getContentResolver();
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(phoneNumber));
Cursor cursor = mResolver.query(uri, new String[] {
PhoneLookup.DISPLAY_NAME, PhoneLookup._ID }, null, null, null);
String contactId = "";
if (cursor.moveToFirst()) {
do {
contactId = cursor.getString(cursor
.getColumnIndex(PhoneLookup._ID));
} while (cursor.moveToNext());
}
cursor.close();
cursor = null;
return contactId;
}
/*
* Returns contact's name
*/
private String getContactName(String contactId, Context context) {
String[] projection = new String[] { Contacts.DISPLAY_NAME };
Cursor cursor = mResolver.query(Contacts.CONTENT_URI, projection,
Contacts._ID + "=?", new String[] { contactId }, null);
String name = "";
if (cursor.moveToFirst()) {
name = cursor.getString(0);
}
cursor.close();
cursor = null;
return name;
}
use the code below :
public void readContacts(){
ContentResolver cr = parent.getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
Contact tempcontact=new Contact();
contactsList.add(tempcontact);
String id=cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name=cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
tempcontact.setId(cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID)));
tempcontact.setName(name);
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Log.e("DATA","name : " + name + ", ID : " + id);
// get the phone number
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
if(pCur.getString(
pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))!=null)
{
tempcontact.getPhonenumber().add(pCur.getString(
pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
}
// System.out.println("phone" + phone);
// Log.e("phone",phone);
}
pCur.close();
// get email and type
Cursor emailCur = cr.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{id}, null);
while (emailCur.moveToNext()) {
// This would allow you get several email addresses
// if the email addresses were stored in an array
String email = emailCur.getString(
emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
tempcontact.getEmail().add(emailCur.getString(
emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA)));
String emailType = emailCur.getString(
emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
Log.e("Data","Email " + email + " Email Type : " + emailType);
}
emailCur.close();
String addrWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] addrWhereParams = new String[]{id,
ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE};
Cursor addrCur = cr.query(ContactsContract.Data.CONTENT_URI,
null, null, null, null);
while(addrCur.moveToNext()) {
tempcontact.setPoBox((addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POBOX))));
tempcontact.setPoBox(addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET)));
tempcontact.setCity(addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY)));
tempcontact.setRegion(addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION)));
tempcontact.setPostalCode(addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE)));
tempcontact.setCountry((addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY))));
tempcontact.setType(addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE)));
// Do something with these....
}
addrCur.close();
String[] projection = {ContactsContract.CommonDataKinds.Photo.PHOTO};
Uri uri = (Uri)ContactsContract.Data.CONTENT_URI;
String where = ContactsContract.Data.MIMETYPE
+ "=" + ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE + " AND "
+ ContactsContract.Data.CONTACT_ID + " = " + id;
Cursor cursor = parent.getContentResolver().query(uri, projection, null, null, null);
if(cursor!=null&&cursor.moveToFirst()){
do{
byte[] photoData = cursor.getBlob(0);
tempcontact.setPhoto(photoData);
//Do whatever with your photo here...
}while(cursor.moveToNext());
}
}
}
}
}
public class Contact {
String id;
String name;
ArrayList<String> phonenumber;
ArrayList<String> email;
String poBox;
String street;
String city;
String state;
String postalCode;
String country;
String type;
String region;
byte[] photo;
public byte[] getPhoto() {
return photo;
}
public Contact() {
// TODO Auto-generated constructor stub
phonenumber=new ArrayList<String>();
email=new ArrayList<String>();
}
public void setPhoto(byte[] photo) {
this.photo = photo;
}
public String getPoBox() {
return poBox;
}
public void setPoBox(String poBox) {
this.poBox = poBox;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ArrayList<String> getPhonenumber() {
return phonenumber;
}
public void setPhonenumber(ArrayList<String> phonenumber) {
this.phonenumber = phonenumber;
}
public ArrayList<String> getEmail() {
return email;
}
public void setEmail(ArrayList<String> email) {
this.email = email;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
}
Cursor phones= getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext())
{
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
phones.close();