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());
}
Related
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().
I am able to retrieve the contact ID, but then later I wish to separately retrieve the phone number based on the contact ID. The code below is returning a null result for the phone number. (I do wish later to retrieve the name and phone number together and populate a view, but I am just trying to get the phone number to work first).
In my onCreate I have this code
String phoneNum = getPhoneNumber(myID);
TextView phoneTextView = (TextView) findViewById(R.id.textViewPhone);
phoneTextView.setText(phoneNum);
This is the method for getPhoneNumber()
protected String getPhoneNumber(String id) {
ArrayList<String> phones = new ArrayList<String>();
Cursor cursor = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id}, null);
while (cursor.moveToNext()) {
phones.add(cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
}
cursor.close();
String phoneNum;
phoneNum = phones.get(0);
return phoneNum;
}//end getPhoneNumber();
}
This produces the error java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0, which I plan on creating some error handling for. But still, I am certain I have the ID from the previous code, so I don't know why the ArrayList returns null. If you would like to see that code, it is also in my onCreate:
Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
if (cursor.getCount() != 0) {
int numContacts = cursor.getCount();
ArrayList<String> idList = new ArrayList<>();
Random rand = new Random();
int randomNum = rand.nextInt(numContacts);
while (cursor.moveToNext()) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
idList.add(id);
}
myID = idList.get(randomNum);
String myString = Integer.toString(randomNum);
TextView myTextView = (TextView) findViewById(R.id.textViewID);
myTextView.setText(myString);
if (myID != null) {
myTextView.setText(myID);
} else {
myTextView.setText("Try Again!");
}
} else {
Toast.makeText(getApplicationContext(), "Your have no contacts.", Toast.LENGTH_SHORT).show();
}
cursor.close();
// You can fetch the Contact Number and Email With Following Methods.
String phone = getPhoneNumber(ContactId);
String email = getEmail("" + ContactId);
private String getPhoneNumber(long id) {
String phone = null;
Cursor phonesCursor = null;
phonesCursor = queryPhoneNumbers(id);
if (phonesCursor == null || phonesCursor.getCount() == 0) {
// No valid number
//signalError();
return null;
} else if (phonesCursor.getCount() == 1) {
// only one number, call it.
phone = phonesCursor.getString(phonesCursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
} else {
phonesCursor.moveToPosition(-1);
while (phonesCursor.moveToNext()) {
// Found super primary, call it.
phone = phonesCursor.getString(phonesCursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
break;
}
}
return phone;
}
private Cursor queryPhoneNumbers(long contactId) {
ContentResolver cr = getContentResolver();
Uri baseUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI,
contactId);
Uri dataUri = Uri.withAppendedPath(baseUri,
ContactsContract.Contacts.Data.CONTENT_DIRECTORY);
Cursor c = cr.query(dataUri, new String[]{ContactsContract.CommonDataKinds.Phone._ID, ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.IS_SUPER_PRIMARY, ContactsContract.RawContacts.ACCOUNT_TYPE,
ContactsContract.CommonDataKinds.Phone.TYPE,
ContactsContract.CommonDataKinds.Phone.LABEL},
ContactsContract.Data.MIMETYPE + "=?",
new String[]{ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE}, null);
if (c != null && c.moveToFirst()) {
return c;
}
return null;
}
private String getEmail(String id) {
String email = "";
ContentResolver cr = getContentResolver();
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
email = emailCur.getString(
emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
// String emailType = emailCur.getString(
// emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
}
emailCur.close();
return email;
}
I have not been able to successfully retrieve code based on the Contact ID - but this post gave me a clue: Retrieving a phone number with ContactsContract in Android - function doesn't work
I have altered my original code to query on DISPLAY_NAME instead and things are working now. Here is the method I am using to retrieve the phone number:
private String retrieveContactNumber(String contactName) {
Log.d(TAG, "Contact Name: " + contactName);
Cursor cursorPhone = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " = ? AND " +
ContactsContract.CommonDataKinds.Phone.TYPE + " = " +
ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE,
new String[]{contactName},
null);
if (cursorPhone.moveToFirst()) {
contactNumber = cursorPhone.getString(cursorPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
cursorPhone.close();
Log.d(TAG, "Contact Phone Number: " + contactNumber);
return contactNumber;
}
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
I wrote an app that needs to read the contacts from the user's phone. Since I've put it on the market, a few users have told me that my app cannot read their contact list (it pops up an error message saying it can't get the contact list).
For roughly 80% of the users, everything works fine, but others have this problem.
In my MainActivity, I call the method: GetContacts()
If that method returns no contacts, then I call: GetContacts2()
If the app still can't get the contacts, then it pops up the error message. Below are the two methods I'm using. Some of the phones, this doesn't work, are Droid X2 and HTC Incredible.
I'm also setting the required API level to 8 in my manifest, so that eliminates older phones. I also do not have log files from these users.
NOTE: I've removed extra code that simply puts the contacts in an array for simplicity's sake.
Any ideas on why these methods don't work on all phones?
Any help would be greatly appreciated!!
Mark
private void GetContacts()
{
try
{
Context context = getApplicationContext();
Cursor cursor = context.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
while (cursor.moveToNext())
{
contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (Integer.parseInt(hasPhone)==1)
{
Cursor phone = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId,null, null);
while (phone.moveToNext())
{
phoneNo = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
phoneType = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
}
}
}
}
catch (Exception e)
{
}
}
private void GetContacts2()
{
try
{
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if (cur.getCount() > 0)
{
while (cur.moveToNext())
{
contactId = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
contactName = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
if (Integer.parseInt(cur.getString(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[]{contactId}, null);
while (pCur.moveToNext())
{
phoneNo = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
phoneType = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
}
pCur.close();
}
}
}
}
}
catch (Exception e)
{
}
}
I agree. Exceptions are definitely not meant to be tossed aside. They're exceptions; they indicate that something is seriously wrong and needs to be looked at. I recommend you at least log them, so that users that run into the problems can send you a LogCat. If you don't want your users to have to go through that trouble, write data to a file on the SD card (public), so that they can access it and send it to you.
//declaration
Cursor cursor;
int cNameIndex = 0;
int cNumIndex = 0;
String [] arrPosDrawn= null;
//oncreate
TelephonyManager telMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
int simState = telMgr.getSimState();
switch (simState) {
case TelephonyManager.SIM_STATE_ABSENT:
AlertDialog.Builder alert = new AlertDialog.Builder(
ContactList.this);
alert.setMessage("Please insert Sim card.")
.setTitle("Alert")
.setNeutralButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
}
}).show();
break;
case TelephonyManager.SIM_STATE_READY:
cursor = refreshContactsCursor();
//contacts.setAdapter(new EfficientAdapter(this));
break;
}
//function
public Cursor refreshContactsCursor()
{
cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
startManagingCursor(cursor);
cursor.moveToFirst();
cNameIndex = cursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME);
cNumIndex = cursor.getColumnIndex(ContactsContract.Data.DATA1);
arrPosDrawn = new String[cursor.getCount() - 1];
for (int j=0; j < arrPosDrawn.length; j++)
{
arrPosDrawn[j] = "";
}
return cursor;
}
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();