Reading contacts on Android 2.2 - android

I'm using the following code to read phone contact names and numbers on Android 2.2.
What i want to do is go reading each contact name and number and append that to a Stringbuilder.
Presently I'm able to get the contact name, but there's some trouble getting the contact numbers.
How can I achieve this? Please provide a sample snippet to get the numbers.
public class main extends Activity {
/** Called when the activity is first created. */
public static StringBuilder s = new StringBuilder();
public static String number= new String();// = new String();
public static String contact = new String();
public final String phonenumber = new String();
public String formattedPhoneNumber = new String();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//-----------code to run when button is clicked-------------------
EditText textfield = (EditText) findViewById(R.id.textfield);
Cursor people = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
Cursor cursor = getContentResolver().query(Phone.CONTENT_URI, new String[]{Phone.NUMBER}, null,null, null);
if(cursor != null) {
if(cursor.getCount() > 0) {
cursor.moveToFirst();
formattedPhoneNumber = cursor.getString( cursor.getColumnIndex(Phone.NUMBER) );
//Log.d("TestActivity", String.format("The selected phone number is: %s", formattedPhoneNumber));
}
cursor.close();
while(people.moveToNext()) {
int nameFieldColumnIndex = people.getColumnIndex(PhoneLookup.DISPLAY_NAME);
contact = people.getString(nameFieldColumnIndex);
int numberFieldColumnIndex = people.getColumnIndex(PhoneLookup.NUMBER);
//umber = people.getString(numberFieldColumnIndex);
}
people.close();
//--------------code for getting phone number---
textfield.setText("hello: "+contact+" "+ formattedPhoneNumber);
//+String.valueOf(number));
//---------------end of code-----------------------------
}
};});}}

Copied from here:
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
"DISPLAY_NAME = '" + NAME + "'", null, null);
if (cursor.moveToFirst()) {
String contactId =
cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
//
// Get all phone numbers.
//
Cursor phones = cr.query(Phone.CONTENT_URI, null,
Phone.CONTACT_ID + " = " + contactId, null, null);
while (phones.moveToNext()) {
String number = phones.getString(phones.getColumnIndex(Phone.NUMBER));
int type = phones.getInt(phones.getColumnIndex(Phone.TYPE));
switch (type) {
case Phone.TYPE_HOME:
// do something with the Home number here...
break;
case Phone.TYPE_MOBILE:
// do something with the Mobile number here...
break;
case Phone.TYPE_WORK:
// do something with the Work number here...
break;
}
}
phones.close();
}
cursor.close();

Related

How can i get only all mobile numbers from android phone book?

That's my code , which give me all number of my android device like mobile numbers, whatsapp numbers and landline numbers. But i want only mobile number and landline numbers from android phone book into my application. How can i get only mobile number and landline number of every contact name?
private void addContactsInList() {
// TODO Auto-generated method stub
Cursor cursor = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, null, null, null);
try {
ContactsListClass.phoneList.clear();
} catch (Exception e) {
}
while (cursor.moveToNext()) {
String phoneName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
int phoneId = cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
Contact cp = new Contact();
cp.setName(phoneName);
cp.setNumber(phoneNumber);
cp.setId(phoneId);
ContactsListClass.phoneList.add(cp);
// Log.e("add to list", "content" + phoneId +phoneName +phoneNumber);
}
cursor.close();
lv = new ListView(context);
lv.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
llContainer.addView(lv);
Collections.sort(ContactsListClass.phoneList, new Comparator<Contact>() {
#Override
public int compare(Contact lhs,
Contact rhs) {
return lhs.getName().compareTo(
rhs.getName());
}
});
contactAdapter = new ContactsAdapter(MainActivity.this,
ContactsListClass.phoneList);
lv.setAdapter(contactAdapter);
inside your while loop, put something like this:
while (phoneCursor.moveToNext()) {
phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
//String number = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
int type = phoneCursor.getInt(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
switch (type) {
case ContactsContract.CommonDataKinds.Phone.TYPE_HOME:
// do something with the Home number here...
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE:
output.append("\n Phone number:" + phoneNumber);
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_WORK:
// do something with the Work number here...
break;
}
}
as seen in this answer
Uri personUri = ContentUris.withAppendedId(People.CONTENT_URI, personId);
Uri phonesUri = Uri.withAppendedPath(personUri, People.Phones.CONTENT_DIRECTORY);
String[] proj = new String[] {Phones._ID, Phones.TYPE, Phones.NUMBER, Phones.LABEL}
Cursor cursor = contentResolver.query(phonesUri, proj, null, null, null);
if(cursor != null && cursor.moveToFirst()){
do{
String number = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
int type = phoneCursor.getInt(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
switch (type) {
case ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE:
break;
}
}while(cursor.moveToNext());
}

android get contacts detail such as number and thumbnail

i use of this code that can get contact's number and contact's thumbnail , but this is not suitable and take to long to load and prepare contacts .
please help me to improve performance of this code :
List<Contact_Pojo> list = new ArrayList<Contact_Pojo>();
ContentResolver cr = getActivity().getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
null, null, Phone.DISPLAY_NAME + " ASC");
int i = 0;
if (cur.moveToFirst()) {
while (cur.moveToNext()) {
Cursor phoneCursor = getActivity()
.getContentResolver()
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[] { ContactsContract.CommonDataKinds.Phone.NUMBER, },
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?",
new String[] { cur.getString(cur
.getColumnIndex(ContactsContract.Contacts._ID)) },
null);
if (phoneCursor.moveToFirst()) {
Contact_Pojo personContact = new Contact_Pojo();
/*
* Id
*/
personContact.setId(cur.getString(1));
/*
* Name
*/
personContact
.setName(cur.getString(cur
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
/*
* Photo ID
*/
personContact
.setImageUrl(cur.getString(cur
.getColumnIndex(ContactsContract.Contacts.PHOTO_THUMBNAIL_URI)));
/*
* Number
*/
personContact.setNumber(phoneCursor.getString(0));
//
list.add(personContact);
}
phoneCursor.close();
}
}
cur.close();
return list;
Update 4/4/2015
it is slow because it has getting all column from contact provider , in this table has +20 column that take many time .
How about using AsyncTaskLoader,
write this code when you want to get contacts list
getLoaderManager() or getSupportLoaderManager().initLoader(int id, Bundle args, LoaderManager.LoaderCallbacks<D> loadingCallback)
public class LoadingCallback implements LoaderManager.LoaderCallbacks<Void> {
#Override
public Loader<Void> onCreateLoader(int i, Bundle bundle) {
// Show your dialog;
return new InitializeContactsTask(context, (ArrayList) contactList, mAdapter);
}
#Override
public void onLoadFinished(Loader<Void> voidLoader, Void aVoid) {
// UI Work here after background task and hide dialog.
}
#Override
public void onLoaderReset(Loader<Void> voidLoader) {
}
}
and
public class InitializeApplicationsTask extends AsyncTaskLoader<Void> {
#Override
protected void onStartLoading() {
forceLoad();
}
#Override
public Void loadInBackground() {
// Query the contacts here and return null
return null;
}
}
It's slow because, you are getting all column from contact provider, so use projection to get only those column which are required. like
String[] projection = {
ContactsContract.Contacts.DISPLAY_NAME
// this is just example, add fields that required
} ;
can you please tell me what is purpose of second query ? because here is my result of getting contact
and my method for getting all contact is
#SuppressLint("InlinedApi")
public void readContacts() {
long l1 = System.currentTimeMillis();
Log.d("DEBUG",
"starting readContacts() time " + l1);
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
Contact_pojo cp = new Contact_pojo();
String Contact_Id = cur.getString(cur
.getColumnIndex(ContactsContract.Contacts._ID));
String Contact_Name = cur
.getString(cur
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String photothumb = "";
try {
photothumb = cur
.getString(cur
.getColumnIndex(ContactsContract.Contacts.PHOTO_THUMBNAIL_URI));
if (photothumb != null
&& !photothumb.toString().equalsIgnoreCase("")) {
cp.setImageUri(photothumb);
}
} catch (Exception e) {
e.printStackTrace();
}
cp.setId(Contact_Id);
cp.setName(Contact_Name);
Cursor phones = cr.query(Phone.CONTENT_URI, null,
Phone.CONTACT_ID + " = " + Contact_Id, null, null);
while (phones.moveToNext()) {
String number = phones.getString(phones
.getColumnIndex(Phone.NUMBER));
int type = phones.getInt(phones.getColumnIndex(Phone.TYPE));
Log.d("DEBUG", "number " + number + " type " + type);
cp.setNumber(number);
}
phones.close();
contactList.add(cp);
}
}
long l2 = System.currentTimeMillis();
Log.d("DEBUG",
"Finished readContacts() time " + l2);
Log.d("DEBUG","Total contact loaded "+contactList.size()+" within "+ (l2 - l1) + "ms");
}
Don't use double query, this is taking too much time if device have lots of contacts and it's not working in some device also...
You can also fetch contact with single query..
Use below code..
public void fetchContacts()
{
String[] projection = new String[] {
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.HAS_PHONE_NUMBER,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID};
String _ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
String DISPLAY_NAME = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ? Contacts.DISPLAY_NAME_PRIMARY : Contacts.DISPLAY_NAME;
String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
Cursor cursor = mActivity.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
projection, ContactsContract.CommonDataKinds.Phone.HAS_PHONE_NUMBER + "=?", new String[] { "1" },
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
System.out.println("contact size.."+cursor.getCount());
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String contact_id = cursor.getString(cursor.getColumnIndex( _ID ));
String name = cursor.getString(cursor.getColumnIndex( DISPLAY_NAME ));
String phoneNumber = cursor.getString(cursor.getColumnIndex(NUMBER));
System.out.println(" name : "+name);
System.out.println(" number : "+phoneNumber);
}
}
}
Check below links for get contact photo.
ContactsContract.Contacts.Photo
Getting a Photo from a Contact

Pick a number from calllog without repeating the same number

I want user to select a number from calllog and that number get selected and come in the activity. So I created custom calllog list. I used this code but it is not showing the call log list in right order
first thing it is showing the callhistory of the first number fully that it gets in the calllog list
second I wnt to show the name also, I tried a lot but I am not able to do
Can anyone tell what amendments i make in this code to make it right
The code I used is:
String[] callLogFields = { android.provider.CallLog.Calls._ID,
android.provider.CallLog.Calls.NUMBER,
android.provider.CallLog.Calls.CACHED_NAME };
String viaOrder = android.provider.CallLog.Calls.DATE + " DESC";
String WHERE = android.provider.CallLog.Calls.NUMBER + " >0"; /*filter out private/unknown numbers */
final Cursor callLog_cursor = this.getContentResolver().query(
android.provider.CallLog.Calls.CONTENT_URI, callLogFields,
WHERE, null, viaOrder);
AlertDialog.Builder myversionOfCallLog = new AlertDialog.Builder(this);
android.content.DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int item) {
callLog_cursor.moveToPosition(item);
Log.v("number", callLog_cursor.getString(callLog_cursor
.getColumnIndex(android.provider.CallLog.Calls.NUMBER)));
callLog_cursor.close();
}
};
myversionOfCallLog.setCursor(callLog_cursor, listener,
android.provider.CallLog.Calls.NUMBER);
myversionOfCallLog.setTitle("Choose from Call Log");
myversionOfCallLog.create().show();
You can add the Contact Numbers in a Set, which will prevent adding duplicate contact numbers. Then add the Set's data to listview as you want.
Set<String> setNumbers = new HashSet<String>();
String callNumber = cursor.getString(cursor.getColumnIndex(
android.provider.CallLog.Calls.NUMBER));
setNumbers.add(callNumber);
Hope this helps.
For saving numbers without duplicates, as MysticMagic suggested, use 'Set' as per the link given in the comment.
For getting the contact name from the phone number, use code :
(Reference)
private String getContactName(Context context, String number) {
String name = null;
// define the columns I want the query to return
String[] projection = new String[] {
ContactsContract.PhoneLookup.DISPLAY_NAME,
ContactsContract.PhoneLookup._ID};
// encode the phone number and build the filter URI
Uri contactUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
// query time
Cursor cursor = context.getContentResolver().query(contactUri, projection, null, null, null);
if(cursor != null) {
if (cursor.moveToFirst()) {
name = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
Log.v(TAG, "Started uploadcontactphoto: Contact Found # " + number);
Log.v(TAG, "Started uploadcontactphoto: Contact name = " + name);
} else {
Log.v(TAG, "Contact Not Found # " + number);
}
cursor.close();
}
return name;
}
Also refer here for another method to fetch name in phone call history
Uri allCalls = Uri.parse("content://call_log/calls");
Cursor c = managedQuery(allCalls, null, null, null, null);
String num= c.getString(c.getColumnIndex(CallLog.Calls.NUMBER));// for number
String name= c.getString(c.getColumnIndex(CallLog.Calls.CACHED_NAME));// for name
String duration = c.getString(c.getColumnIndex(CallLog.Calls.DURATION));// for duration
int type = Integer.parseInt(c.getString(c.getColumnIndex(CallLog.Calls.TYPE)));// for call type, Incoming or out going
Finally this is the code that worked with the help of MysticMagic and Nishanthi Grashia
Set setA;
setA = new HashSet();
public void getCallLog() {
try {
final String[] projection = null;
final String selection = null;
final String[] selectionArgs = null;
final String sortOrder = "DATE DESC";
final Cursor cursor = this.getContentResolver().query(
Uri.parse("content://call_log/calls"), projection,
selection, selectionArgs, sortOrder);
if (cursor != null) {
// Loop through the call log.
while (cursor.moveToNext()) {
// Common Call Log Items
String callNumber = cursor
.getString(cursor
.getColumnIndex(android.provider.CallLog.Calls.NUMBER));
setA.add(callNumber);
}
generateList();
}
} catch (Exception e) {
}
}
#SuppressLint("NewApi")
private void generateList() {
// TODO Auto-generated method stub
try {
Object[] calllist = new String[setA.size()];
calllist = setA.toArray();
String scalllist[] = Arrays.copyOf(calllist, calllist.length,
String[].class);
for (int i = 0; i < scalllist.length; i++) {
scalllist[i] = scalllist[i] + " "
+ getContactName(this, scalllist[i]);
}
final Dialog d = new Dialog(this);
d.setContentView(R.layout.dialog1);
d.setTitle("Choose from Call Log...");
final ListView lv1 = (ListView) d.findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1,
scalllist);
lv1.setAdapter(adapter);
lv1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
String clickednumber[] = (lv1.getItemAtPosition(arg2)
.toString()).split(" ");
usernumber.setText(clickednumber[0]);
try {
username.setText(clickednumber[1]);
} catch (ArrayIndexOutOfBoundsException e) {
username.setText(" ");
}
d.dismiss();
}
});
d.show();
} catch (Exception e) {
}
}
private String getContactName(Context context, String number) {
String name = null;
try {
// define the columns I want the query to return
String[] projection = new String[] {
ContactsContract.PhoneLookup.DISPLAY_NAME,
ContactsContract.PhoneLookup._ID };
// encode the phone number and build the filter URI
Uri contactUri = Uri.withAppendedPath(
ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(number));
// query time
Cursor cursor = context.getContentResolver().query(contactUri,
projection, null, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
name = cursor
.getString(cursor
.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
} else {
name = " ";
}
cursor.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return name;
}

Cannot get contacts from phone book android

I'm create an application to get all contacts from phone book of Android device. I synch my contacts list from Gmail to android device and I see all contacts in phone book. But when running application, cannot get any contacts from phone book.
Here is my code
MainActivity.java
public class MainActivity extends Activity {
private TextView outputText;
TextView txtViewContactsInfor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
outputText =(TextView)findViewById(R.id.textView2);
txtViewContactsInfor = (TextView) findViewById(R.id.txtViewContactsInfor);
Import_contacts_from_address_book();
}
private void Import_contacts_from_address_book() {
// TODO Auto-generated method stub
String phoneNumber = null;
String email = null;
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 PHONECONTACT_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 EMAIL = ContactsContract.CommonDataKinds.Email.DATA;
StringBuffer output = new StringBuffer();
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(CONTENT_URI, null, null, null, null);
System.out.println("---------------------->"+cursor.getCount());
if(cursor.getCount() >0){
int aa = cursor.getCount();
while(cursor.moveToNext()){
String contact_id = cursor.getString(cursor.getColumnIndex(_ID));
String name = cursor.getString(cursor.getColumnIndex(DISPLAY_NAME));
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(HAS_PHONE_NUMBER)));
if(hasPhoneNumber > 0 ){
output.append("\nFirst Name: "+name);
// Query and loop for every phone number of the contact
Cursor phoneCursor = contentResolver.query(PHONECONTENT_URI, null, PHONECONTACT_ID + "=?", new String[]{contact_id}, null);
while(phoneCursor.moveToNext()){
phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
output.append("\n Phone number: "+phoneNumber);
}
phoneCursor.close();
// Query and loop for every email of the contact
Cursor emailCurosr = contentResolver.query(EMAILCONTENT_URI, null, EMAILCONTACT_ID+"=?",new String[]{contact_id},null);
while(emailCurosr.moveToNext()){
email = emailCurosr.getString(emailCurosr.getColumnIndex(EMAIL));
output.append("\nEmail: "+email);
}
emailCurosr.close();
}
output.append("\n");
}
cursor.close();
}
outputText.setText(output.toString());
}
I debug in cursor.getCount and see "544 contact" was found. But
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(HAS_PHONE_NUMBER))); always zero.
I dont know why.
You might have a lot contacts without number, because contacts are stored in multiple columns.
I simplified and modified your code to count rows with and with out numbers and let it run on my phone:
private void readContacts() {
Cursor c = getContentResolver()
.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
int foundWithNumber = 0;
int foundWithOutNumber = 0;
if (c.moveToFirst()) {
int idHasNumber = c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER);
do {
boolean hasNumber = c.getInt(idHasNumber) > 0;
if (hasNumber) {
++foundWithNumber;
} else {
++foundWithOutNumber;
}
} while (c.moveToNext());
}
Log.d(TAG, "foundWithNumber: " + foundWithNumber);
Log.d(TAG, "foundWithOutNumber: " + foundWithOutNumber);
c.close();
}
The ouput on my phone is:
MainActivity D foundWithNumber: 184
D foundWithOutNumber: 303
So, I guess, you just looked at the wrong rows. ;)
You nead add Read contact permission in Android manifest
android.permission.READ_CONTACTS

without extends of class activity how to getget email id's from contacts and get phone no from contacts?

hi all how to implement coding for get email id's from contacts and get phone no from contacts show me the way to overcome from this problem
note: class doesn't have extends Activity and oncreate() method also so kindly help me to go forward
Your class doesnot have extends Activity or onCreate() method. So pass the context parameter from the class which extends Activity to this class.
sudo code
Class A extends Activity{
new ClassB(this);
}
here Class B does not extends Activity.
But write the following method to gwt contacts and email id in class B
public static void getContactNumbers(Context context) {
String contactNumber = null;
int contactNumberType = Phone.TYPE_MOBILE;
String nameOfContact = null;
ArrayList<ContactNumberBean> phoneContacts = new ArrayList<ContactNumberBean>();
ContentResolver cr = context.getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur
.getColumnIndex(BaseColumns._ID));
nameOfContact = cur
.getString(cur
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer
.parseInt(cur.getString(cur
.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor phones = cr
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?", new String[] { id },
null);
while (phones.moveToNext()) {
contactNumber = phones.getString(phones
.getColumnIndex(Phone.NUMBER));
contactNumberType = phones.getInt(phones
.getColumnIndex(Phone.TYPE));
phoneContacts
.add(new ContactNumberBean(nameOfContact,
contactNumber, contactNumberType));
}
phones.close();
}
}
}// end of contact name cursor
cur.close();
}
/**
*
* This method is responsible to get native contacts and corresponding email
* id (ApplicationConstants.emailContacts)
*
* #param context
*/
public static void getContactEmails(Context context) {
String emailIdOfContact = null;
int emailType = Email.TYPE_WORK;
String contactName = null;
ArrayList<ContactEmailBean> emailContacts = new ArrayList<ContactEmailBean>();
ContentResolver cr = context.getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur
.getColumnIndex(BaseColumns._ID));
contactName = cur
.getString(cur
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
// Log.i(TAG,"....contact name....." +
// contactName);
cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?", new String[] { id }, null);
Cursor emails = cr.query(Email.CONTENT_URI, null,
Email.CONTACT_ID + " = " + id, null, null);
while (emails.moveToNext()) {
emailIdOfContact = emails.getString(emails
.getColumnIndex(Email.DATA));
// Log.i(TAG,"...COntact Name ...."
// + contactName + "...contact Number..."
// + emailIdOfContact);
emailType = emails.getInt(emails
.getColumnIndex(Phone.TYPE));
emailContacts
.add(new ContactEmailBean(contactName,
emailIdOfContact, emailType));
}
emails.close();
}
}// end of contact name cursor
cur.close();
}
Write two bean class
EmailBean
public class ContactEmailBean {
String emailType = null;
String nameOfContact = null;
String emailIdOfContact = null;
public ContactEmailBean(String nameOfContact, String emailIdOfContact,
int emailType) {
switch (emailType) {
case Email.TYPE_HOME:
this.emailType = "HOME";
// do something with the Home number here...
break;
case Email.TYPE_MOBILE:
this.emailType = "MOBILE";
// do something with the Mobile number here...
break;
case Email.TYPE_WORK:
this.emailType = "WORK";
// do something with the Work number here...
break;
default:
this.emailType = "OTHER";
break;
}
this.nameOfContact = nameOfContact;
this.emailIdOfContact = emailIdOfContact;
}
public String getNameOfContact() {
return this.nameOfContact;
}
public String getEmailType() {
return this.emailType;
}
public String getEmailIdOfContact() {
return this.emailIdOfContact;
}
}
ContactNumberBean
public class ContactNumberBean {
String phoneNumberType = null;
String nameOfContact = null;
String contactNumber = null;
public ContactNumberBean(String nameOfContact, String contactNumber,
int contactNumberType) {
switch (contactNumberType) {
case Phone.TYPE_HOME:
this.phoneNumberType = "HOME";
// do something with the Home number here...
break;
case Phone.TYPE_MOBILE:
this.phoneNumberType = "MOBILE";
// do something with the Mobile number here...
break;
case Phone.TYPE_WORK:
this.phoneNumberType = "WORK";
// do something with the Work number here...
break;
case Phone.TYPE_WORK_MOBILE:
this.phoneNumberType = "WORK";
break;
case Phone.TYPE_FAX_HOME:
this.phoneNumberType = "FAX";
break;
default:
this.phoneNumberType = "OTHER";
break;
}
this.nameOfContact = nameOfContact;
this.contactNumber = contactNumber;
}
public String getNameOfContact() {
return this.nameOfContact;
}
public String getPhoneNumberType() {
return this.phoneNumberType;
}
public String getContactNumber() {
return this.contactNumber;
}
}
Have a look at this code!
btn_existing_contacts.setOnClickListener(new OnClickListener() {
public void onClick(View v){
Intent intent_contacts = new Intent(Intent.ACTION_PICK,ContactsContract.Contacts.CONTENT_URI);
/*contacts.setAction(android.content.Intent.ACTION_VIEW);
contacts.setData(People.CONTENT_URI);*/
startActivityForResult(intent_contacts, 0);
//displayContacts();
}
});
after returning from contacts screen,
#Override
protected void onActivityResult(int requestCode, int resultCode,Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
String name,mailid,id;
switch(requestCode)
{
case 0:
{
if(resultCode == RESULT_OK )
{
Uri contactdata = data.getData();
Cursor cur = managedQuery(contactdata, null, null, null, null);
if(cur.moveToFirst())
{
id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
Cursor emailCur = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",new String[]{id}, null);
emailCur.moveToFirst();
String email = emailCur.getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
name = cur.getString(cur.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
//mailid = cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
//mailid = cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Email._ID));
//Toast.makeText(context_contact, "Name:"+name+"\nmailid:"+email, Toast.LENGTH_SHORT).show();
Intent intent_add_invitees = new Intent(<ClassContext>,<ur classname>.class);
intent_add_invitees.putExtra("invitee_name", name);
intent_add_invitees.putExtra("invitee_mailid", email);
setResult(RESULT_OK, intent_add_invitees);
finish();
}
}
}
}
}
The Send_invitations .class is the activity where I am using these contacts

Categories

Resources