Contacts information in android

Основы 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’ом.

Читайте также:  Djvu viewer для андроида

Теперь попробуем переложить это на код. За таблицы и их поля отвечает, как я уже говорил, класс 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

Читайте также:  Android studio авторизация github

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 contacts’ phone number in Android

My code is as below:

I get contacts’ name success, but get phone number fail in GetPhoneNumber() .
The phones.getCount() always equal 0.
How can I modify?

6 Answers 6

Android Contact API For 2.0

For more information see this link

You need permission like —

Then, Calling the Contact Picker

Old question but I don’t see the following answer here.

Use column index ContactsContract.CommonDataKinds.Phone.NUMBER to retreive the phone number from the cursor.

Читайте также:  Настройки камера андроид что это

Call contact picker on any button and use the below code :

|*| Add in : AndroidManifest.xml

|*| Add in : activity_name.java

Your can add this code on your Activity class:

Not the answer you’re looking for? Browse other questions tagged android cursor or ask your own question.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.12.3.40888

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Read all contacts’ phone numbers in android

I’m using this code to retrieve all contact names and phone numbers:

However, this will only return the primary number for each contact, but I want to get the secondary numbers as well. How can i do this?

15 Answers 15

Following code shows an easy way to read all phone numbers and names:

NOTE: getContentResolver is a method from the Activity context.

You can read all of the telephone numbers associated with a contact in the following manner:

Please note that this example (like yours) uses the deprecated contacts API. From eclair onwards this has been replaced with the ContactsContract API.

This code shows how to get all phone numbers for each contact.

In case it helps, I’ve got an example that uses the ContactsContract API to first find a contact by name, then it iterates through the details looking for specific number types:

You can get all phone contacts using this:

check complete example HERE.

800 contacts, the codes in this answer run for 89 ms, but the other way (query for contact id then phone numbers for each id) used 23 000 ms !

You can get all the contact all those which have no number and all those which have no name from this piece of code

One thing can be done you have to give the permission in the manifest for contact READ and WRITE After that you can create the model class for the list which can be use to add all the contact here is the model class

In the same way just get their other numbers using the other «People» references

Accepted answer working but not given unique numbers.

See this code, it return unique numbers.

This one finally gave me the answer I was looking for. It lets you retrieve all the names and phone numbers of the contacts on the phone.

I fixed my need belove

Note: After giving permissions at manifest some mobile phones can deny if so you need to go Settings—> Applications—> find your application click on it and turn On the permissions needed

Load contacts in background using CursorLoader:

Here’s how to use ContentsContract API to fetch your contacts in your Phone Book. You’ll need to add these permissions in your AndroidManifest.xml

Then, you can run this method to loop through all your contacts.

Here’s an example to query fields like Name and Phone Number, you can configure yourself to use CommonDataKinds, it query other fields in your Contact.

Code to get contact name (Ascending order) and number

Источник

Оцените статью