- Основы Contacts API в Android
- Введение
- Структура данных
- Работаем с контактами
- Android Contacts : Get Contact Details Phone Number Programmatically
- 1. Android Get Contact Details Programmatically
- Step 2: Updating AndroidManifest.xml file
- Step 3: Updating activity_main.xml file
- Step 4: Preparing MainActivity.java class
- Step 5: Description of MainActivity.java
- 2. Android Get Contact List And Display in ListView
- Step 2: Updating AndroidManifest.xml file
- Step 3: Adding ListView Item file
- Step 4: Creating a model class
- Step 5: Making a custom adapter class
- Step 6: Updating MainActivity
- Step 7: Describing MainActivity.java class
- 4 thoughts on “Android Contacts : Get Contact Details Phone Number Programmatically”
- How to get Contact ID, Email, Phone number in one SQLite query ? Contacts Android Optimization
- 2 Answers 2
- Some constants
- 1 Contact
- 2 Contact Details
- 3 Combining
- Correction/Improvement
- Android Contacts provider get only phone contacts with all emails
- Answers
Основы Contacts API в Android
Введение
Начиная с версии 5 API Android SDK интерфейс работы с контактами изменился, а основной контент провайдер Contacts и все его составляющие получили черную метку @Deprecated. Теперь за работу с контактами отвечает провайдер ContactsContract. Эти изменения связаны с изменением структуры хранения контактов, более адаптированной для Android устройств, которым требуется хранить контакты из множества разных источников и предоставлять их пользователю как единую сущность. Ведь сегодня, определенный контакт на нашем мобильном устройстве это не только имя и номер телефона, мы можем захотеть сохранить eMail, Im, Twitter, Facebook аккаунт определенного человека, и при этом, мы не хотим чтобы у нас нас появилось миллион непонятных записей. Поэтому новый Contacts API позволяет Android агрегировать похожие контакты и представлять их пользователю в одной записи, а также связывать контакт с разного рода данными.
Структура данных
На устройстве основная информация о контактах хранится в трех таблицах, на деле их там конечно больше, но мы рассмотрим основные три: contacts, raw_contacts и data. Чтобы было более наглядно я набросал простую схему в Dia.
В таблице contacts хранятся агрегированные контакты, каждая запись в этой таблице представляет собой пользовательский контакт (единую сущность) – объединение одного или нескольких сырых (необработанных) контактов из таблицы raw_contacts. Как видно на схеме, связь между этими таблицами один ко многим (1-N). Одна запись в таблице raw_contacts представляет собой так называемый сырой контакт. Сырой контакт, на языке Android, означает какой-то конкретный набор данных для определенного контакта. Но сами основные данные в этой таблице не хранятся, они хранятся в таблице data, и связь между raw_contacts и data также один ко многим. В таблице data хранятся непосредственно данные. Причем каждая строка этой таблицы это набор данных определенного типа для контакта. Какого именно типа данные хранятся в строке определяется столбцом mimetype_id, в котором содержится id типов данных определенных в таблице mimetype(например vnd.android.cursor.item/name, vnd.android.cursor.item/photo). Теперь разберемся во всем по подробней и с примерами.
Работаем с контактами
Хорошо, допустим мы хотим добавить контакт (Robert Smith, моб.тел. 11-22-33), как нам это сделать? В таблицу contacts мы сами, явно, не можем добавить контакт, так как система сама формирует эту таблицу агрегируя похожие raw_contacts. Идентичность контактов система определяет в основном по имени (одинаковые имена, фамилии и т.п.), но и по другим критериям, каким именно и как ими управлять можно посмотреть в документации. То есть, если мы добавим raw_contact нашего Роберта (Robert Smith) и свяжем его с данными типа vnd.cursor.android.item/phone, а потом у нас появится “похожий”, для системы, Robert Smith связанный с данными типа vnd.cursor.android.item/email и еще один с данными типа vnd.cursor.android.item/photo, то у нас в контактах будет один Robert Smith с фотографией, мобильным и email’ом.
Теперь попробуем переложить это на код. За таблицы и их поля отвечает, как я уже говорил, класс ContactsContract и его внутренние классы и интерфейсы. Например интерфейсом к таблице raw_contacts является класс ContactsContract.RawContacts, а за таблицу data класс ContactsContract.Data. Будьте внимательны когда изучаете их константы – интерфейсы к столбцам – обращайте внимание на метки read/write и read only.
Из написанного выше следует, что для начала, мы должны добавить сырой контакт, а потом связывать его с данными. Добавить пустой контакт можно так:
В контактах у вас должен появиться пустой (Unknown) контакт, ни с чем не связанный. Добавим ему имя. Чтобы это сделать, мы должны связать наш новый контакт с новыми данными используя его id, который можно достать из прошлого запроса. Основные интерфейсы к полям таблицы данных содержаться в классе-контейнере ContactsContract.CommonDataKinds и его внутренних классах и интерфейсах. Например, сейчас нам понадобиться
класс ContactsContract.CommonDataKinds.StrucruredName содержащий нужные нам константы для добавления имени, а также константу MIME типа, которой мы пометим наше поле в таблице данных.
Если мы добавим контакт таким образом, то в списке контактов у нас появиться Robert Smith. Теперь идем дальше, добавим нашему контакту еще и телефон. Для этого нам понадобиться класс ContactsContract.CommonDataKinds.Phone, который является интерфейсом к данным телефонного номера.
Теперь в контактах у нас есть Robert Smith которому можно позвонить. Но вот так добавлять контакт и данные к нему, в несколько запросов, дорого и накладно. Поэтому существует класс ContentProviderOperation, который позволяет построить запрос, который выполнит все наши операции за одну транзакцию. Именно им и рекомендуют пользоваться. Вот так можно добавить нашего Роберта используя ContentProviderOperation.
Вот таким образом в Android можно добавлять контакты. Будьте осторожны используя ContentProviderOperation, так как слишком большой запрос может долго выполняться. Вообще все операции лучше производить в отдельном потоке, потому, что у пользователя, например, может быть слабый телефон и много контактов.
В остальном все другие операции выполняются обычным образом, используя те провайдеры, которые вам необходимы, с некоторыми оговорками. Например, удаление контакта из таблицы contacts удалит все raw_contacts с ним связанные и т.д.
Вот так можно попробовать найти нашего Роберта в контактах:
На этом хотелось бы завершить статью, все же это были только основные сведения о Contacts API в Andoid. Я надеюсь мне удалось описать здесь основные принципы, а вся конкретика зависит от того, что вам необходимо сделать в процессе работы. Можно просто руководствоваться этими принципами и находить в официальной документации интерфейсы которые вам нужны для работы. Успехов!
Источник
Android Contacts : Get Contact Details Phone Number Programmatically
Hello, all learners. Welcome to Android Contacts tutorial with example.
In this get contact list details Android Studio programmatically tutorial we will learn how to retrieve contact name, phone number, email, etc. information in Android app programmatically.
Two examples are there in this post as per the below.
1. Android Get Contact Details Programmatically
Contact based application will need to access contact details, this tutorial will guide you for this purpose.
First, check the output of get contact list details Android Studio programmatically then we will implement it.
Step 2: Updating AndroidManifest.xml file
add required permissions between …. tag.
Final code for AndroidManifest.xml file
Step 3: Updating activity_main.xml file
We will make user interface for getting name, phone number and email address.
Three textviews are used for this purpose.
Copy and paste below source code in activity_main.xml file
Step 4: Preparing MainActivity.java class
Add following source code in MainActivity.java class
Step 5: Description of MainActivity.java
Following source code will open contact list on button click.
After clicking on contact list item, onActivityResult() method is called.
Below line will get name of contact
Below source code will check whether contact has a phone number or not.
If contact has phone number, then it will be got by following
Following source code will take the Email address.
Then finally, all text are set in respected textviews
So all for get contact list details android studio programmatically example tutorial. Thank you.
2. Android Get Contact List And Display in ListView
Welcome to android get contact list with phone numbers tutorial.
Get contact list in Android Studio example guides you to get a contact list and show in the custom listview.
Get contact list in Android example will show how to show all contacts alphabetically.
First, go through the output, then we will develop with Android Studio.
Step 2: Updating AndroidManifest.xml file
add required permissions between …. tag.
Final code for AndroidManifest.xml file
Step 3: Adding ListView Item file
Make a new layout resource file named “lv_item.xml”
Step 4: Creating a model class
Create a new class named “ContactModel.”
Step 5: Making a custom adapter class
Prepare a new class and give a name as “CustomAdapter.”
Step 6: Updating MainActivity
Update activity_main.xml as below source code
Update MainActivity.java class as following
Step 7: Describing MainActivity.java class
Let’s make an eye on below source code
We are using Cursor class to get details about contacts.
We will store contact’s name and phone number in two different variables.
After that, we will create a object of ContactModel class and will add this object to the contactModelArrayList.
After getting all the contacts information, we will set whole information in ListView.
So the end for get contact list in android studio programmatically tutorial. Thank you.
4 thoughts on “Android Contacts : Get Contact Details Phone Number Programmatically”
hi,
i got problem,
when i open contact list, list is open successfully, but when i press back without click on contact, app got crash
See your logcat, which line is making crash?
Hi, this code was so help full for me, i need some more help from u, i need to select specific number of a person, for eg: i have saved someones name with two or more numbers so how could i select specific number. if u can help me, let me know, thank you.
I also need to dig out about selecting specific number.
I will make separate tutorial on this topic in near future.
Источник
How to get Contact ID, Email, Phone number in one SQLite query ? Contacts Android Optimization
I want to fetch All Contacts atleast with one phone Number, also I want all Phone Numbers and All emails for every Contact.
If there are more than 1000 contacts in my Device, it is taking too much time. How can I get All Data in single query, rather than doing two additional queries for each contact?
Or is there any other way to optimize?
Thank you in Advance.
2 Answers 2
ICS: When you query from Data.CONTENT_URI you have all the rows from the associated Contact already joined — i.e. this would work:
If you are targeting 2.3 you need to account for the fact that HAS_PHONE_NUMBER is not available through the joins used when querying Data .
This could, for instance, be solved either by skipping your requirement that the contact must have a phone number and instead settle for «any contact with at least a phone number or an e-mail address»:
If that is not an option you can always go for a horribly hacky sub-select:
or solve it by using two Cursor s:
I went through the exact same problem. Since then I build my own solution which is inspired from this post yet a bit different. Now I’d like to share it as my first StackOverFlow answer 🙂
Its quite similar to the double cursor approach suggested by Jens. The idea is to
1- fetch relevant contact from the Contacts table
2- fetch relevant Contacts information (mail, phone, . )
3- combine these results
The «relevant» is up to you of course but the important point is the performance ! Besides, I’m sure other solutions using well suited SQL query might as well do the job but here I only want to use the Android ContentProvider Here is the code :
Some constants
1 Contact
Here I require that the Contacts must have DISPLAY_NAME free of «@» and that their informations match a given string (these requirement can of course be modified). The result of the following method is the first cursor :
This query is quite performant as you’ll see !
2 Contact Details
Now let’s fetch Contact informations. At this point, I dont make any link between the already fetched Contact and the retrieved information : I just fetch all informations form the Data table. Yet, to avoid useless info I still require DISPLAY_NAMES free of «@» and since I’m interested in email and phone I require that the data MIMETYPE to be either MAIL_TYPE or PHONE_TYPE (see Constants). Here is the code :
Once again you will see that this query is quite fast.
3 Combining
Now let’s combine both Contact and their respective informations. The idea is to use HashMap(Key, String) where Key is the Contact id and String is whatever you like (name, email, . ).
First, I run through the Contact cursor (which is alphabetically ordered) and store names and picture uri in two different HashMap. Note also that I store all Contact id’s in a List in the very same order that Contacts appear in the cursor. Lets call this list contactListId
I do the same for the Contact informations (mail and email). But now I take care of the correlation between the two cursor : if the CONTACT_ID of an email or phone does not appear in contactListId it is put aside. I check also if the email has already been encountered. Notice that this further selection can introduce asymmetries between the Name/Picture content and the Email/Phone HashMap content but don’t worry.
Eventually, I run over the contactListId list and build a list of Contact object taking care of the fact that : a contact must have information (keySet condition) and that the contact must have at least a mail or an email (the case where mail == null && phone == null may appear if the contact is a Skype contact for instance). And here is the code :
The Contact object definition is up to you.
Hope this will help and thanks for the previous post.
Correction/Improvement
I forgot to check the phone key set : it should rather looks like
with the phone keySet
I why not add an empty contact cursor check like :
Источник
Android Contacts provider get only phone contacts with all emails
I need to get all phone contacts and their email address and photo uri:
This is what am doing:
My problem am getting all contacts including gmail contacts, i dont want gmail contacts to be included. And the time taken is also very slow. How do i optimize this, I know its taking time coz i am using many cursors.. but dont know how to make a single cusror that can give me name email number photo uri . Thanks!
Answers
You should be able to get all the information needed in one query on Data.CONTENT_URI, Check out «android.provider.ContactsContract.Data» table and the examples on how to query different types of data Email,Phone,Photo etc. http://developer.android.com/reference/android/provider/ContactsContract.Data.html
Should bring you all the information you need regarding one specific contactId, you could theoretically ask for all contacts and sort the information yourself.
As for filtering gmail contacts this is a more complex issue, take a look at ACCOUNT_NAME / TYPE http://developer.android.com/reference/android/provider/ContactsContract.RawContacts.html parameter and a discussion regarding this issue here: What is the default Account Type / Name for contacts on Android Contact Application?
All contact information in Android 2.0 is stored in a single database table. So you can get all the information you need in a single query:
The just iterate through the data and check Data.MIMETYPE column. For example, if this column has StructuredPostal.CONTENT_ITEM_TYPE value, then you can get StructuredPostal fields from this column.
There are multiple considerations that could go into deciding what the best approach might be.
First, do you have an idea about the maximum number of items in the recycler’s list? If it is just a handful, maybe you could ditch the RecyclerView approach and just add your CompundView into a container hosted by a ScrollView .
Secondly — is the layout of each item fairly complicated (a.k.a. are there many TextViews , ImageViews etc. in it)? If yes, maybe you could take an approach that would resemble an ExpandableListView — show a summary as each list item and expand to the full layout of the item on click.
Thirdly — if none of the above is acceptable and you still want to go the current approach — don’t construct/add your view in the binding method. Do it in the onCreateViewHolder , when the system expects you to construct your view (I don’t know for sure but by the time you’re called on onBindViewHolder your view might have been already added to the hierarchy and any hierarchical change to it has a ripple effect on its containers — but don’t take my word for it, I don’t actually know the view is already added, it is just an assumption). You will have to assign each item a different type, so that in onCreateViewHolder you could match the view type with the supporting data (for the addition of the corresponding number of child views); create the view from scratch each time — this way you don’t need to call on removeAllViews . Something like(I left out parts of the adapter that are not relevant to the case):
Источник