Lib Phone / Contacts

optimist

Member
Licensed User
Longtime User
From where do you get the Contact.Id in the phone-lib?

If i do a simple query (code like below) then i get other Id's. I can not imagine why. Do you have an idea?

B4X:
Uri person = ContactsContract.Contacts.CONTENT_URI;
String[] projection = new String[] {
   ContactsContract.Contacts.DISPLAY_NAME,
   ContactsContract.Contacts._ID
   };
Cursor cur = ba.activity.managedQuery(person, projection, null, null, null);

Reason for the question:
I wrote an lib to extend your contact related functions (for example: access adresses of a contact). But with different Id's its hard to coordinate.
Could you please explain how you get the contact-Id's in your phone lib?

Thanks
 
Last edited:

Erel

B4X founder
Staff member
Licensed User
Longtime User
Note that the Contacts object doesn't use ContactsContract as it is not supported by Android 1.6.

Here is the code:
B4X:
@ShortName("Contacts")
@Permissions(values={"android.permission.READ_CONTACTS"})
public class ContactsWrapper {
    private static final String[] people_projection = {Contacts.People.TIMES_CONTACTED,
        Contacts.Phones.NUMBER, Contacts.People.LAST_TIME_CONTACTED,
        Contacts.People.DISPLAY_NAME, Contacts.People.NAME, Contacts.People.NOTES, Contacts.People.STARRED, BaseColumns._ID};
    
    /**
     * Returns a List of Contact objects with all the contacts. This list can be very large.
     */
    public List GetAll() {
        return getAllContacts(null, null);
    }
    /**
     * Returns a List of Contact objects with all contacts matching the given name.
     *Name - The name to search for.
     *Exact - If True then only contacts with the exact name value (case sensitive) will return
     *, otherwise all contacts names that include the Name string will return (case insensitive).
     */
    public List FindByName(String Name, boolean Exact) {
        if (!Exact)
            return getAllContacts(Contacts.People.NAME + " LIKE ?", new String[] {"%" + Name + "%"});
        else
            return getAllContacts(Contacts.People.NAME + " = ?", new String[] {Name});
    }
    /**
     * Returns a List of Contact objects with all contacts matching the given email.
     *Email - The email to search for.
     *Exact - If True then only contacts with the exact email address (case sensitive) will return
     *, otherwise all contacts email addresses that include the Email string will return (case insensitive).
     */
    public List FindByMail(String Email, boolean Exact) {
        ContentResolver cr = BA.applicationContext.getContentResolver();
        String sel, args;
        if (!Exact) {
            sel = " LIKE ?";
            args = "%" + Email + "%";
        }
        else {
            sel = " = ?";
            args = Email;
        }
        Cursor crsr = cr.query(Contacts.ContactMethods.CONTENT_EMAIL_URI, new String[] {Contacts.ContactMethods.PERSON_ID,
                Contacts.ContactMethods.DATA}, Contacts.ContactMethods.DATA + sel, new String[] {args}, null);
        StringBuilder sb = new StringBuilder();
        while (crsr.moveToNext()) {
            for (int i = 0;i < crsr.getColumnCount();i++) {
                sb.append(crsr.getString(0)).append(",");
            }
        }
        int count = crsr.getCount();
        crsr.close();
        if (count == 0) {
            List l = new List();
            l.Initialize();
            return l;
        }
        sb.setLength(sb.length() - 1);
        String selection = BaseColumns._ID +  " IN (" + sb.toString() + ")";
        return getAllContacts(selection, null);
    }
    /**
     * Returns the Contact with the specified Id.
     * Returns Null if no matching contact found.
     */
    public Contact GetById(int Id) {
        List l = getAllContacts(BaseColumns._ID + " = ?", new String[] {String.valueOf(Id)});
        if (l.getSize() == 0)
            return null;
        else
            return (Contact) l.Get(0);
    }
    private List getAllContacts(String selection, String[] args) {

        ContentResolver cr = BA.applicationContext.getContentResolver();
        Cursor crsr = cr.query(Contacts.People.CONTENT_URI, people_projection, selection, args, null);
        List l = new List();
        l.Initialize();
        HashMap<String, Integer> m = new HashMap<String, Integer>();
        for (int col = 0;col < crsr.getColumnCount();col++) {
            m.put(crsr.getColumnName(col), col);
        }
        
        while (crsr.moveToNext()) {
            Contact contact = new Contact(
                    crsr.getString(m.get(Contacts.People.DISPLAY_NAME)),
                    crsr.getString(m.get(Contacts.Phones.NUMBER)),
                    crsr.getInt(m.get(Contacts.People.STARRED)) > 0,
                    crsr.getInt(m.get(BaseColumns._ID)),
                    crsr.getString(m.get(Contacts.People.NOTES)),
                    crsr.getInt(m.get(Contacts.People.TIMES_CONTACTED)),
                    crsr.getLong(m.get(Contacts.People.LAST_TIME_CONTACTED)),
                    crsr.getString(m.get(Contacts.People.NAME)));
            l.Add(contact);
        }
        crsr.close();
        return l;
    }
 
Upvote 0

optimist

Member
Licensed User
Longtime User
google is crackbrained.
we have two interfaces, one is deprecated and lacks functionality, the other is not is not supported by Android 1.6. :sign0148:

And both use different ID's for the same Datarecords :BangHead: , so migration is as hart as possible.

I personally choosed for me to use the future-proof ContactsContract and will loose customers with older phones.
 
Upvote 0

peacemaker

Expert
Licensed User
Longtime User
I'm trying to add new Contacts, get all the Contacts and search among Notes field.
Emulator 2.2 works OK with just created new contacts.

But final testing with a real device 2.3 with lots of Contacts (internal and SIM card's) - GetAll returns .... 5 contacts total only :-(

How to understand ?
 
Last edited:
Upvote 0

peacemaker

Expert
Licensed User
Longtime User
Erel, creating new contact is not a problem, by this miscUtil lib, or calling system's intent as i do.
Problem is to get all existing contacts to search among them any info.
What are contact IDs to get them byID ? How to make sure that all listed ?
 
Upvote 0

RandomCoder

Well-Known Member
Licensed User
Longtime User
I too am unable to use GetAll to retrieve all the contacts from a phone using Phone library v1.60 and I've downloaded the miscutil library as it was suggested this uses a different API but it is only for adding/removing contacts or have I missed something?

The phone I am using is an LG 'Optimus' GT540 which I believe is running Android v2.1 and the code I use is shown below (taken from a tutorial here on the forum)...
B4X:
Sub btnContacts_Click
Dim PhoneContacts As Contacts
Dim ContactsList, ListOfNames As List
   ContactsList = PhoneContacts.GetAll
   ListOfNames.Initialize
   'Create a list with the contacts names
   For i = 0 To ContactsList.Size - 1
        Dim c As Contact
        c = ContactsList.Get(i) 'fetch the Contact from the original list
        If c.DisplayName.IndexOf("@") = -1 Then 'remove email only contacts
            ListOfNames.Add(c.DisplayName)
        End If
    Next
   EmergencyContacts=InputMultiList(ListOfNames,"Contacts")
End Sub

Can anyone offer any help as to why I'm unable to retrieve the phone contacts?

Thanks,
RandomCoder

PS If I place a breakpoint at the command to GetAll contacts I can see that an empty array is returned.
 
Last edited:
Upvote 0

peacemaker

Expert
Licensed User
Longtime User
Tha same problem with LG P500 (olnly 5 contacts are found among really lot) - how to get all the contacts for sure ?
 
Upvote 0

RandomCoder

Well-Known Member
Licensed User
Longtime User
Is anyone able to offer any advise as to how we can get all contacts from the phone?
Is the problem limited to LG or have any other users had problems with other phones?

If unable to get the phone's contact list then I'm going to have to create my own contacts list which just seems a little pointless considering the numbers are already there in the phone :BangHead:

Thanks,
RandomCoder
 
Upvote 0

Kevin

Well-Known Member
Licensed User
Longtime User
Complete stab in the dark and if I am completely wrong just ignore my worthless advice. :)

Is it possible that the problem stems from Google contacts vs Exchange contacts? In other words.... I have about 3 or 4 contacts in my GOOGLE contacts list but I have hundreds of contacts in my EXCHANGE contacts list. While the two can be synced, I don't have mine setup to do so (caused problems such as duplicates). I haven't played with this library though so I have no idea how it works.

For all I know, this function is supposed to return ALL contacts no matter which source they are from, in which case I am completely wrong so you can ignore me.
 
Upvote 0

csgoh

Member
Licensed User
Longtime User
Me Too!

I can't retrieve any contacts from my LG P500 phone too! Any workaround? Is that means I can't develop any apps which rely on contacts? Please advise!

:BangHead:

:sign0163:
 
Upvote 0

quasimidi

New Member
Licensed User
Longtime User
LG Optimus - contacts

The GT540 and P500 stores your contacts on two location: (in the 20x factory firmware) which is either SIM and at your Google account.

So the GetAll function fetches only the SIM contacts (that is the default (0) contact location). Just for the test: export all your google contacts to the sim.
It will be fetched by GetAll.

Regs,

Robert
 
Upvote 0

mcmanu

Active Member
Licensed User
Longtime User
Hi

I get an error --> contact=listofcontacts.get(i)
java.lang.indexoutofboundsexception
invalid index 37

here is my code

Dim Contacts2 As Contacts2
Dim listOfContacts As List
listOfContacts = Contacts2.GetAll(True,False)
For i = 0 To listOfContacts.Size <------------ Here i removed -1 because i want to display all contacts and not only the last one
Dim Contact As Contact
Contact = listOfContacts.Get(i)
Log(Contact) 'will print the fields to the LogCat
Dim photo As Bitmap
photo = Contact.GetPhoto
If photo <> Null Then imageview10.Bitmap=photo
Dim emails As Map
emails = Contact.GetEmails
If emails.Size > 0 Then Log("Email addresses: " & emails)
Dim phones As Map
phones = Contact.GetPhones
If phones.Size > 0 Then Log("Phone numbers: " & phones)
Next
listview2.AddTwoLinesAndBitmap2(Contact.Name,Contact.PhoneNumber,imageview10.Bitmap,phones)
listview2.ScrollingBackgroundColor =Colors.Transparent
imageview10.Visible=True
 
Last edited:
Upvote 0

mcmanu

Active Member
Licensed User
Longtime User
Erel

Sorry erel i edited my last post because now it works but i get and error (code above)
 
Upvote 0

mcmanu

Active Member
Licensed User
Longtime User
Hi

Oh okay that looks good :)
I will test it later :) Thank you :)


Now i tested it and i get only my last conatct
When i remove -1 than i get this out of bound expeption
 
Last edited:
Upvote 0

vb1992

Well-Known Member
Licensed User
Longtime User
Dim Contacts2 As Contacts2
Dim listOfContacts As List
listOfContacts = Contacts2.GetAll(True,False)

For i = 0 To listOfContacts.Size - 1
Dim Contact As Contact
Contact = listOfContacts.Get(i)
Log(Contact) 'will print the fields to the LogCat
Dim photo As Bitmap
photo = Contact.GetPhoto
If photo <> Null Then imageview10.Bitmap=photo
Dim emails As Map
emails = Contact.GetEmails
If emails.Size > 0 Then Log("Email addresses: " & emails)
Dim phones As Map
phones = Contact.GetPhones
If phones.Size > 0 Then Log("Phone numbers: " & phones)

listview2.AddTwoLinesAndBitmap2(Contact.Name,Conta ct.PhoneNumber,imageview10.Bitmap,phones)
listview2.ScrollingBackgroundColor =Colors.Transparent
imageview10.Visible=True


Next
 
Upvote 0
Top