Categorie
Information and Communications Technology

Programmatically create contacts on Android 1.6 Donut (API Level 4) targetting HTC Tattoo

Here is the code i used:

    private void addPeople(String name, List<String> homeNumbers, List<String> mobileNumbers) {
        //insert contact
        ContentValues peopleContentValues = new ContentValues();
        peopleContentValues.put(Contacts.People.NAME, name);
        //WARNING: this is for HTC to indicate the contact type
        //extra_group = 0 [google contact]
        //extra_group = 1 [??: maybe SIM contact]
        //extra_group = 2 [phone concact]
        peopleContentValues.put("extra_group", 2);
        Uri peopleUri = getContentResolver().insert(Contacts.People.CONTENT_URI, peopleContentValues);
        
        //get contact id [i need it to add phone numbers to it]
        Cursor cursorPeople = getContentResolver().query(peopleUri, new String[]{Contacts.People._ID}, null, null, null);
        cursorPeople.moveToNext();
        long peopleId = cursorPeople.getLong(0);
        
        //add phones
        for (String num : mobileNumbers) {
            addPhoneToPeople(peopleId, Contacts.Phones.TYPE_MOBILE, num);    
        }
        for (String num : homeNumbers) {
            addPhoneToPeople(peopleId, Contacts.Phones.TYPE_HOME, num);    
        }
    }
    
    private void addPhoneToPeople(long peopleId, int type, String number) {
        if (number != null && !number.equals("")) {
            ContentValues phoneContentValues = new ContentValues();
            phoneContentValues.put(Contacts.Phones.PERSON_ID, peopleId);
            phoneContentValues.put(Contacts.Phones.TYPE, type);
            phoneContentValues.put(Contacts.Phones.NUMBER, number);
            getContentResolver().insert(Contacts.Phones.CONTENT_URI, phoneContentValues);
        }
    }