I have a ListView with a custom Lazy Adapter attached. I pull contacts from the phone and display them in my list. I am having an issue dealing with multiple numbers. If one contact has multiple numbers with different types they appear as different contacts as shown below:
Here is the code for getting my contact list:
public LazyAdapter getContactList(){
ContentResolver cr = mContext.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(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query(Phone.CONTENT_URI,null,Phone.CONTACT_ID +" = ?",new String[]{id}, null);
while (pCur.moveToNext()) {
String phoneType = "";
int type = pCur.getInt(pCur.getColumnIndexOrThrow(Phone.TYPE));
switch (type){
case Phone.TYPE_HOME:
phoneType = "Home";
break;
case Phone.TYPE_MOBILE:
phoneType = "Mobile";
break;
case Phone.TYPE_WORK:
phoneType = "Work";
break;
case Phone.TYPE_FAX_HOME:
phoneType = "Home Fax";
break;
case Phone.TYPE_FAX_WORK:
phoneType = "Work Fax";
break;
default:
phoneType = "Other";
break;
}
String phoneNo = pCur.getString(pCur.getColumnIndex(Phone.NUMBER));
map = new HashMap<String, String>();
map.put(KEY_CONTACT_NAME, name);
map.put(KEY_CONTACT_NUM, phoneType + ": " + phoneNo);
//map.put(KEY_CONTACT_IMAGE, getString(getPhotoUri(id)));
contactList.add(map);
}
pCur.close();
}
}
}
adapter = new LazyAdapter(getActivity(), contactList);
return adapter;
}
And here is my lazy adapter
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.contact_list, null);
TextView contactName = (TextView)vi.findViewById(R.id.contactName); // title
TextView contactNum = (TextView)vi.findViewById(R.id.contactNum); // artist name
ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image); // thumb image
HashMap<String, String> contact = new HashMap<String, String>();
contact = data.get(position);
// Setting all values in listview
contactName.setText(contact.get(ContactFragment.KEY_CONTACT_NAME));
contactNum.setText(contact.get(ContactFragment.KEY_CONTACT_NUM));
return vi;
}
How can I display multiple numbers under one contact if they have multiple numbers?
Thanks
Figured out the answer. I just added the position number to the phone number I had. When adding the number to the LazyAdapter I looped through the array list and added the numbers like so:
ContactActivity
public LazyAdapter getContactList(){
ContentResolver cr = mContext.getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
map = new HashMap<String, String>();
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
map.put(KEY_CONTACT_NAME, name);
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query(Phone.CONTENT_URI,null,Phone.CONTACT_ID +" = ?",new String[]{id}, null);
while (pCur.moveToNext()) {
String phoneType = "";
int type = pCur.getInt(pCur.getColumnIndexOrThrow(Phone.TYPE));
switch (type){
case Phone.TYPE_HOME:
phoneType = "Home";
break;
case Phone.TYPE_MOBILE:
phoneType = "Mobile";
break;
case Phone.TYPE_WORK:
phoneType = "Work";
break;
case Phone.TYPE_FAX_HOME:
phoneType = "Home Fax";
break;
case Phone.TYPE_FAX_WORK:
phoneType = "Work Fax";
break;
default:
phoneType = "Other";
break;
}
String phoneNo = pCur.getString(pCur.getColumnIndex(Phone.NUMBER));
map.put(KEY_CONTACT_NUM + pCur.getPosition(), phoneType + ": " + phoneNo);
}
contactList.add(map);
pCur.close();
}
}
}
adapter = new LazyAdapter(getActivity(), contactList, "Contact");
return adapter;
}
Lazy adapter
TextView contactName = (TextView)vi.findViewById(R.id.contactName); // name
TextView contactNum = (TextView)vi.findViewById(R.id.contactNum); // number
HashMap<String, String> contact = new HashMap<String, String>();
contact = data.get(position);
// Setting all values in listview
contactName.setText(contact.get(ContactFragment.KEY_CONTACT_NAME));
for(int i = 0; i < (contact.size() - 1); i++){
contactNum.setText(contactNum.getText() + contact.get(ContactFragment.KEY_CONTACT_NUM + i) + "\n");
}
Related
I am getting contact details of a person according to the account name which is working fine but i get the exception for those contacts which have name but not numbers. I am also getting the contact ids for those but when i fetch the details using contact_id from Phone cursor it causes exception
private void displayAllContactsByType(String accountName) //account-name: Mobikwik
{
Cursor rawCursor = null;
rawCursor = cResolver.query(
ContactsContract.RawContacts.CONTENT_URI,
new String[]{ContactsContract.RawContacts.CONTACT_ID},
ContactsContract.RawContacts.ACCOUNT_NAME + "= ? AND "+ContactsContract.RawContacts.CONTACT_ID + " != 0",
new String[]{accountName},
ContactsContract.Contacts.DISPLAY_NAME_PRIMARY + " COLLATE LOCALIZED ASC");
int contactIdColumn = rawCursor.getColumnIndex(ContactsContract.RawContacts.CONTACT_ID);
int rawCursorCount = rawCursor.getCount();
int total = 1;
Utils.Log("Raw Size", " " + rawCursorCount);
while (rawCursor.moveToNext()) {
contactId = rawCursor.getLong(contactIdColumn);
storeContactDetails(contactId );
}
rawCursor.close();
}
from above methods i am getting contacts id which are used to get the data in below method.
private void storeContactDetails( Long contactId) //e.g contact_id-2512
{
Cursor phones = null;
String[] projection = new String[]{
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.Contacts.LOOKUP_KEY,
Phone.HAS_PHONE_NUMBER,
Phone.TYPE,
Phone.LAST_TIME_USED
};
phones = cResolver.query(Phone.CONTENT_URI,
projection,
Phone.CONTACT_ID + " = ? ",
new String[]{String.valueOf(contactId)},
null);
phones.moveToFirst();
getResultsFromPhoneCursor(phones);
}
public void getResultsFromPhoneCursor(Cursor phones) {
String email_Id = "";
String contactType = "";
String lastTimeUsed = "";
HashMap<String,String> contactTypeWithNumber=new HashMap<>();
try {
String hasPhone = "";
display_name = "";
phoneNumber = "";
display_name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));// THIS LINE IS CAUSING EXCEPTION HERE
lastTimeUsed = convertLongToDateFormat(phones.getString(phones.getColumnIndex(Phone.LAST_TIME_USED)));
hasPhone = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.HAS_PHONE_NUMBER));
if (hasPhone.equalsIgnoreCase("1"))
hasPhone = "true";
else
hasPhone = "false";
if (Boolean.parseBoolean(hasPhone)) {
String lookupKey = phones.getString(phones.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Cursor emails = cResolver.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, new String[]{ContactsContract.CommonDataKinds.Email.DATA},
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contactId, null, null);
while (emails.moveToNext()) {
email_Id = emails.getString(emails
.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
}
emails.close();
do {
phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
int type = phones.getInt(phones.getColumnIndex(Phone.TYPE));
switch (type) {
case 0:
contactType = "whatsapp";
break;
case Phone.TYPE_HOME:
contactType = "home";
break;
case Phone.TYPE_MOBILE:
contactType = "mobile";
break;
case Phone.TYPE_WORK:
contactType = "work";
break;
case Phone.TYPE_OTHER:
contactType = "other";
break;
case Phone.TYPE_WORK_PAGER:
contactType = "pager";
break;
case Phone.TYPE_MMS:
contactType = "mms";
break;
case Phone.TYPE_MAIN:
contactType = "main";
break;
case Phone.TYPE_FAX_HOME:
contactType = "fax";
break;
case Phone.TYPE_FAX_WORK:
contactType = "fax-home";
break;
}
if(contactList.contains(new ContactsWrapper(contactId, display_name, lookupKey, false, email_Id, lastTimeUsed,null))) {
try {
HashMap<String,String>contactTypeMapPrevious=contactList.get(contactList.size()-1).getContactTypeWithNumber();
if (!contactTypeMapPrevious.get(contactType).replace(" ","").equals(this.phoneNumber.replace(" ",""))) {
contactTypeWithNumber.put(contactType, phoneNumber);
}
else
{
if(!contactTypeWithNumber.containsKey(contactType)&& contactTypeMapPrevious.size()<=1)
contactTypeWithNumber.put(contactType, phoneNumber);
}
} catch (Exception e) {
e.printStackTrace();
}
}
else
contactTypeWithNumber.put(contactType,phoneNumber);
}
while (phones.moveToNext());
contactList.add(new ContactsWrapper(contactId, display_name, lookupKey, false, email_Id, lastTimeUsed,contactTypeWithNumber));
phones.close();
}
} catch (Exception e) {
e.printStackTrace();//Cursor Out of Bound Exception here
}
}
Why am i getting this exception even if i have the contact id which not 0 or null. this code works well for contacts that have both name and numbers Please Help Thanks in Advance
I am unable to get all contact ids from the RawContacts table
private void displayAllContactsByType(String accountName)
{//e.g accountName="WHATSAPP"
Cursor rawCursor = null;
rawCursor = cResolver.query(
ContactsContract.RawContacts.CONTENT_URI,
new String[]{ContactsContract.RawContacts.CONTACT_ID},
ContactsContract.RawContacts.ACCOUNT_NAME + "= ?",
new String[]{accountName},
ContactsContract.Contacts.DISPLAY_NAME_PRIMARY + " COLLATE LOCALIZED ASC");
rawCursor.moveToFirst();
int contactIdColumn = rawCursor.getColumnIndex(ContactsContract.RawContacts.CONTACT_ID);
int rawCursorCount = rawCursor.getCount();
int total = 1;
Utils.Log("Raw Size", " " + rawCursorCount);//rawCursorCount is correct here
while (rawCursor.moveToNext()) {
Long contactId = rawCursor.getLong(contactIdColumn);
publishProgress(((total * 100) / rawCursorCount));
progressBar.setProgressNumberFormat("" + total + "/" + rawCursorCount);
storeContactDetails(contactId, accountName);
++total;
//I am facing problem in this method only below code is just for understanding.
}
}
Contact ids are passed to the below method with account name to get the contact details from respective id but contact ids are less compare to the log //Utils.Log("Raw Size", " " + rawCursorCount).
private void storeContactDetails(Long id, String accountName) {
Cursor phones = null;
String[] projection = new String[]{ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.HAS_PHONE_NUMBER,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.Contacts.LOOKUP_KEY,
"account_name",
Phone.TYPE
};
//Cursor c=cResolver.query(ContactsContract.Data.CONTENT_URI,projection,ContactsContract.Data.RAW_CONTACT_ID + " = ?",new String[]{String.valueOf(id)} ,null);
phones = cResolver.query(Phone.CONTENT_URI,
projection,
Phone.CONTACT_ID + " = ?",
new String[]{String.valueOf(id)},
null);
phones.moveToFirst();
getResultsFromPhoneCursor(phones, accountName);
}
public void getResultsFromPhoneCursor(Cursor phones, String accountName) {
int colorcounter = 0;
String[] colorcounter_array = {"#91A46B", "#8BB6B5", "#CAA973", "#8DA6C8", "#D19B8D"};
int color_string;
String email_Id = "";
String contactType = "";
try {
contactId = 0;
String hasPhone = "";
display_name = "";
phoneNumber = "";
contactId = phones.getLong(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
display_name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)).trim();
hasPhone = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.HAS_PHONE_NUMBER));
if (hasPhone.equalsIgnoreCase("1"))
hasPhone = "true";
else
hasPhone = "false";
if (Boolean.parseBoolean(hasPhone)) {
do {
this.accountName = phones.getString(phones.getColumnIndex("account_name"));
phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
int type = phones.getInt(phones.getColumnIndex(Phone.TYPE));
switch (type) {
case Phone.TYPE_HOME:
contactType = "HOME";
break;
case Phone.TYPE_MOBILE:
contactType = "MOBILE";
break;
case Phone.TYPE_WORK:
contactType = "WORK";
break;
}
String lookupKey = phones.getString(phones.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
if (colorcounter < 5) {
color_string = Color.parseColor(colorcounter_array[colorcounter]);
colorcounter++;
} else {
colorcounter = 0;
color_string = Color.parseColor(colorcounter_array[colorcounter]);
colorcounter++;
}
Cursor emails = cResolver.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, new String[]{ContactsContract.CommonDataKinds.Email.DATA},
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contactId, null, null);
while (emails.moveToNext()) {
email_Id = emails.getString(emails
.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
}
emails.close();
if (this.accountName.equalsIgnoreCase(accountName)) {
if (!contactList.contains(new ContactsWrapper(contactId, display_name, phoneNumber, lookupKey, false, color_string, email_Id, contactType)))
contactList.add(new ContactsWrapper(contactId, display_name, phoneNumber, lookupKey, false, color_string, email_Id, contactType));
}
}
while (phones.moveToNext());
phones.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
please help me to solve this case or suggest any other ways to get the contact_ids . Thanks in Advance.
The problem is that you are loosing the first contact you fetch from the db.
The statement rawCursor.moveToFirst(); positions the cursor on the first available result record. The, when you want to iterate over the results, you call rawCursor.moveToNext() inside your loop. The loop condition is executed before it's body, so, you end up moving the cursor to the second row, loosing the first record.
You can fix this by getting rid of rawCursor.moveToFirst().
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());
}
I am working to get all the contacts from phone book and SIM card in my application. I want to store those all contacts in my application SQLite DB. The code with which I am working is working fine in normal conditions. Getting problem in below conditions:
with a contact without name, that is only number.
Contacts from SIM card.
These 2 types of contacts, are not provided to me by my code. I am using the below code:
public void getDefaultContactsToDB(){
CallBackDatabase callbackDB = new CallBackDatabase(RequestCallBack.this);
callbackDB.open();
//clean the database before entering new values.
callbackDB.deleteTable(CallBackDatabase.DATABASE_TABLE);
ContentResolver cr = 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(ContactsContract.Contacts._ID));
Cursor cur1 = cr.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{id}, null);
while (cur1.moveToNext()) {
//to get the contact names
ArrayList<String> numbers= new ArrayList<String>();
String contactNoumber="";
String name=cur1.getString(cur1.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
if(name!=null){
Log.e("Name :", name);
if(name.equalsIgnoreCase("011999999999999999")){
System.out.println("got it");
}
}
//to get the contact email
String email = cur1.getString(cur1.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
if(email!=null)
Log.e("Email", email);
String hasNoumber = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if(Integer.parseInt(hasNoumber)>0){
Cursor pCur = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "
+cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID)),null, null);
int i = 0;
while (pCur.moveToNext()) {
//to get the contact number
contactNoumber = pCur.getString(pCur.getColumnIndex("DATA1"));
if(contactNoumber.equalsIgnoreCase("011999999999999999")){
System.out.println("got it");
}
contactNoumber = Constant.removeSpecialCharacters(contactNoumber);
Log.e("contactNoumber", contactNoumber);
// Getting Phone numbers
String numType = null;
if(pCur.getString(pCur.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)){
switch(pCur.getInt(pCur.getColumnIndex("data2"))){
case ContactsContract.CommonDataKinds.Phone.TYPE_HOME :
numType = "HOME";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE :
numType = "MOBILE";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_WORK :
numType = "WORK";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_OTHER :
numType = "OTHER";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_ASSISTANT :
numType ="OTHER";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_CALLBACK :
numType = "CALLBACK";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_CAR :
numType ="CAR";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_COMPANY_MAIN :
numType = "COMPANY MAIN";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_FAX_HOME :
numType = "FAX HOME";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_FAX_WORK :
numType = "FAX WORK";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_MAIN :
numType = "MAIN";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_ISDN :
numType = "ISDN";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_MMS :
numType = "MMS";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_OTHER_FAX :
numType = "OTHER FAX";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_PAGER :
numType = "PAGER";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_RADIO :
numType = "RADIO";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_TELEX :
numType ="TELEX";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_TTY_TDD :
numType = "TTY TDD";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_WORK_MOBILE :
numType = "WORK MOBILE";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_WORK_PAGER :
numType = "WORK PAGER";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_CUSTOM :
numType = "CUSTOM";
break;
default:
break;
}
}
numbers.add(i, contactNoumber+"("+numType+")");
i++;
}
String numInDB = null;
for (int j = 0; j < i; j++) {
if(j==0)
numInDB =numbers.get(j);
else
numInDB =numInDB + "," +numbers.get(j);
}
if(contactNoumber.length()>0){
if(name!=null){
}else{
name = contactNoumber;
}
callbackDB.InsertContacts(null, name+"="+numInDB, contactNoumber, email);
}
}
}
cur1.close();
}
//CLOSE DB
callbackDB.close();
}
}
Below is the code which shows an easy way to read all phone numbers and names:
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));
}
phones.close();
Also For Sim contact only you can use below code:
private void allSIMContact()
{
try
{
String m_simPhonename = null;
String m_simphoneNo = null;
Uri simUri = Uri.parse("content://icc/adn");
Cursor cursorSim = this.getContentResolver().query(simUri,null,null,null,null);
Log.i("PhoneContact", "total: "+cursorSim.getCount());
while (cursorSim.moveToNext())
{
m_simPhonename =cursorSim.getString(cursorSim.getColumnIndex("name"));
m_simphoneNo = cursorSim.getString(cursorSim.getColumnIndex("number"));
m_simphoneNo.replaceAll("\\D","");
m_simphoneNo.replaceAll("&", "");
m_simPhonename=m_simPhonename.replace("|","");
Log.i("PhoneContact", "name: "+m_simPhonename+" phone: "+m_simphoneNo);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
EDITED:
To get the details of the contacts like home,mobile,fax etc. you need to check for that individually as below:
while (phone_crsr.moveToNext())
{
int phone_type = phone_crsr.getInt(phone_crsr.getColumnIndex(Phone.TYPE));
switch (phone_type)
{
case Phone.TYPE_HOME:
phone_home =phone_crsr.getString(phone_crsr.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Toast.makeText(this, "home"+phone_home, Toast.LENGTH_LONG).show();
break;
case Phone.TYPE_MOBILE:
phone_mob=phone_crsr.getString(phone_crsr.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Toast.makeText(this, "mob"+phone_mob, Toast.LENGTH_LONG).show();
break;
case Phone.TYPE_WORK:
phone_work=phone_crsr.getString(phone_crsr.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Toast.makeText(this, "work"+phone_work, Toast.LENGTH_LONG).show();
break;
}
}
The following code will return all the names of the contact and you can set in text view-
Cursor cursor = null;
String name, phoneNumber,image,email;
try {
cursor = getApplicationContext().getContentResolver()
.query(Phone.CONTENT_URI, null, null, null, null);
int nameIdx = cursor.getColumnIndex(Phone.DISPLAY_NAME);
int phoneNumberIdx = cursor.getColumnIndex(Phone.NUMBER);
int photoIdIdx = cursor.getColumnIndex(Phone.PHOTO_URI);
cursor.moveToFirst();
do {
HashMap<String, String> hashMap = new HashMap<String, String>();
name = cursor.getString(nameIdx);
phoneNumber = cursor.getString(phoneNumberIdx);
image = cursor.getString(photoIdIdx);
//email=cursor.getString(emailIdx);
if(!phoneNumber.contains("*"))
{
hashMap.put("name", "" + name);
hashMap.put("phoneNumber", "" + phoneNumber);
hashMap.put("image", "" + image);
//hashMap.put(email, ""+email);
hashMapsArrayList.add(hashMap);
}
} while (cursor.moveToNext());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null) {
cursor.close();
}
}
myAdapter=new MyAdapter();
listView.setAdapter(myAdapter);
myAdapter.notifyDataSetChanged();
}
The following code will return all the names of the contact
public static Cursor get(Context c){
Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = new String[] { ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME };
String selection = ContactsContract.Contacts.HAS_PHONE_NUMBER
+ " = '1'";
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME
+ " COLLATE LOCALIZED ASC";
Cursor cursor = c.getContentResolver().query(uri, projection,
selection, null, sortOrder);
return cursor;
}
To get all the data you can do the following
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String[] projection = new String[] {
ContactsContract.CommonDataKinds.Phone._ID,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.STARRED,
ContactsContract.CommonDataKinds.Phone.TYPE };
String sortOrder = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
+ " COLLATE LOCALIZED ASC";
Cursor cursor = context.getContentResolver().query(uri, projection,
null, null, sortOrder);
From the cursor you can get all the data
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