Reputation: 161
I am developing a mobile app using Kivy. I would like to access the phone book (contact list). Is there an easy way like accessing the mobile sensors using plyer.
Note: I am not an android expert.
Upvotes: 1
Views: 2622
Reputation: 495
I needed this and searched a lot but couldn't find solution which is full code and understandable. I hope these explanations will be enough to figure out.
Accessing correctly PythonActivity
:
PythonActivity = autoclass("org.kivy.android.PythonActivity")
Accessing Contacts
Java Class:
Contacts = autoclass("android.provider.ContactsContract$Contacts")
Accessing ContactsContract.CommonDataKinds.Phone
Java Class (same):
Kinds = autoclass("android.provider.ContactsContract$CommonDataKinds$Phone")
Creating getContentResolver()
:
cr = PythonActivity.mActivity.getContentResolver()
Now we need to create 2 query. In first, we are going to find ID
and need to use it in second query to find equal NUMBER
. Also need to check is contact has phone number? too. After that we can loop second query to find number:
name_number_dict= {} # Name:Number # Change as you wish..
while (que1.moveToNext()): #Query 1 Loop
if que1.getString(que1.getColumnIndex(Contacts.HAS_PHONE_NUMBER)): #If has number
que2 = cr.query(Kinds.CONTENT_URI, None, Kinds.CONTACT_ID + " = " + que1.getString(que1.getColumnIndex(CONTACTS_ID)), None, None) #Query 2 Loop
while (que2.moveToNext()):
name_number_dict[que1.getString(que1.getColumnIndex(Contacts.DISPLAY_NAME))] = que2.getString(que2.getColumnIndex(Kinds.NUMBER) # Get datas and put in dic.
If you need to check all ColumnNames of query, use query1.getColumnNames()
>> Referance
If you need to find count : query1.getCount()
will be useful.
Upvotes: 0
Reputation: 8041
First thing you'll need permission, add the READ_CONTACTS premission to your buildozer spec.
Now, you should use pyjnius to use the Java SDK like this:
-this is not tested-
PythonActivity=autoclass("org.renpy.android.PythonActivity")
ContactsContract=autoclass("android.provider.ContactsContract")
cr = PythonActivity.mActivity.getContentResolver()
null = None # this will help to convert java examples into python ones :)
cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null)
if (cur.getCount() > 0):
while (cur.moveToNext()):
id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)) #I think this is not DISPLAY_NAME in all versions ...
print("->", id, name)
#you can further query contact by its id
the logic is taken from this answer: android get all contacts
There is also this pull request for plyer that you might want to test: https://github.com/kivy/plyer/pull/125/
Upvotes: 2