3

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:

  1. with a contact without name, that is only number.
  2. 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();
        }
    }
Raynold
  • 443
  • 2
  • 9
  • 28
Sam-In-TechValens
  • 2,501
  • 4
  • 34
  • 67

3 Answers3

5

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;           
             }
            }
GrIsHu
  • 29,068
  • 10
  • 64
  • 102
  • If I want to get SIM + Phone contacts then, Do I need to use the both blocks or the above part only? – Sam-In-TechValens Mar 22 '13 at 04:58
  • You need to use both blocks to get SIM + Phone contacts. – GrIsHu Mar 22 '13 at 05:05
  • let me try it ,,, let you know asap. – Sam-In-TechValens Mar 22 '13 at 05:11
  • The code works fine, but I am getting a small problem in this code.: Suppose, we have a contact SAM in our phone book in which we have 5 numbers like home, mobile, fax etc. In this case, I am getting all number but not continually. I am getting the first 2 numbers then after 3 or 4 contacts I am getting th rest 3 numbers of SAM. Please help me in this. – Sam-In-TechValens Mar 22 '13 at 05:34
  • This code is just to determine the TYPE of number. It will not give me all the numbers of the Any Contact at once. And I am using this code already above. Can you see what mistake I am making in my cursor coz of which I am not getting the numbers without name from my contact list please. – Sam-In-TechValens Mar 22 '13 at 06:39
  • I am not getting question . – GrIsHu Mar 22 '13 at 07:44
  • You just have to keep the switch case inside your `while (pCur.moveToNext()) {` and then check for the type of the phone numbers and return different strings for each mobile,fax,home etc... As i have shown in my answer switch case check that and try out that way. I'm sure you ll get it. – GrIsHu Mar 22 '13 at 07:47
  • You are not getting my question Grishu. 1) In my above pasted code, I am not getting the saved contacts that are not saved with Names (only number field is saved) 2) In your provided code, the contacts which have more then one number, do not return numbers continuosly. – Sam-In-TechValens Mar 22 '13 at 08:39
3

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();

    }
Priyanka
  • 677
  • 5
  • 20
anupam sharma
  • 1,705
  • 17
  • 13
0

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

stinepike
  • 54,068
  • 14
  • 92
  • 112