- Основы Contacts API в Android
- Введение
- Структура данных
- Работаем с контактами
- How to Get Saved Contacts in Android Application using Cursor?
- What we are going to build in this article?
- Step by Step Implementation
- Where Are Contacts Stored on Android and How to Export Them
- Where Are Contacts Stored on Android?
- 1. Contacts Are Stored on Internal Storage
- 2. Contacts on Android Are Stored on SIM Card
- 3. Android Contacts Are Stored on SD Card
- How to Check Where Contacts Is Saved in the Android Phone (for Samsung)
- How to Export Contacts from Android?
- 1. Export Contacts on Android from Google Account
- 2. Export Contacts in Samsung’s Contact App
- 3. Export Contacts from Android through D-Back Android
- Conclusion
Основы 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. Я надеюсь мне удалось описать здесь основные принципы, а вся конкретика зависит от того, что вам необходимо сделать в процессе работы. Можно просто руководствоваться этими принципами и находить в официальной документации интерфейсы которые вам нужны для работы. Успехов!
Источник
How to Get Saved Contacts in Android Application using Cursor?
Phone Contacts are very important source of data for everyone and hence accessing phone contacts is the main feature for many applications like Truecaller to help their users and provide them a better experience. We all have a default application in our mobile to manage contacts but what happens if we will create our own application that will read all the saved contacts and will show them to the user. We can use that application for backup of our contacts. So, in this article, we are going to learn how to develop an application that will read contacts.
Note: A Cursor is a class that contains the result set for a particular query that was made against a database in Android. This class has an API that provides a facility to read the columns which were returned from the query, as well as helps to iterate over the rows of the result set.
What we are going to build in this article?
We will be building a simple application in which we will be displaying a Button and when we will click on that button, and it will add all saved contacts (their names and numbers) into ListView of our application. Note that we have to give permission to our application to read our phone contacts. We will use Java language for developing this project.
Step by Step Implementation
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Источник
Where Are Contacts Stored on Android and How to Export Them
It is easy to find yourself in situations where you need to know the location of your contacts. Android phones are pretty secure when it comes to storing your contact lists. But it is wise to have a backup of them on your computer or on the cloud so that in case you’re ever in an unforeseen situation you can easily retrieve them.
For example, you’ve bought a new phone and need to transfer over the contacts from your old phone to your new Android phone. But you don’t know where are contacts stored on Android. In order to make things easier for you, in this post we’ll guide you on the Android contacts storage location and some useful tips for future reference. Similarly, we’ll also explain how you can export those contacts on Android to your computer or back it up on the cloud.
Where Are Contacts Stored on Android?
So, the big question is where are the contacts stored on your phone? Sure you can see them in the contact list, but which folder are they stored in? Here are the three Android contact storage places where you can look at.
1. Contacts Are Stored on Internal Storage
For any Android phone, the contacts are mostly stored in the internal storage – in case you don’t have an external memory card stored. In most cases, you will only be able to access those contacts if your phone is rooted. There can be many issues when you root your Android phone. However, if the need is urgent, you can find the contacts folder in the directory:
The contacts will be in a SQL file format which will need a database application program to open it. But don’t worry, there is another way to find the Android contacts storage location.
2. Contacts on Android Are Stored on SIM Card
You can also store contacts on your SIM card which can be accessed through the settings of your phone. However, in order to know to restore contacts from the SIM card, you must have exported them to the SIM in the first place.
Nonetheless, here is how you can export contacts to the SIM card:
Go to Settings.
Click on Contacts.
Select the Import/Export Contacts option.
Click on Export to SIM card.
3. Android Contacts Are Stored on SD Card
Another place where contacts can be stored on the Android phone is your external memory card — commonly known as SD card. To check if they are available, remove the SD card from your phone and place it in another phone, and export the contacts from the card to your phone.
How to Check Where Contacts Is Saved in the Android Phone (for Samsung)
Usually, when you save contacts on your phone, they can be stored in different places including your Gmail account, internal memory, or SD card. If you want to know where are contacts stored on a Samsung phone, then you can figure it out easily through the following process:
Open your Contacts app.
Click on Edit for the contact you want to check the location.
Now at the top, you will find where the contact is being saved on your Android phone.
You can also change the location of where your contacts being saved by simply clicking on the Saving To field and selecting the one you need: internal storage, external SD card, etc.
How to Export Contacts from Android?
Now that we’ve gone through all the possible locations where contacts on your Android phone may be stored in, then let’s move onto the next step: we’ll guide you on how to create a backup of your contacts or export them to your computer.
The following methods will help you export contacts from your Android phone.
1. Export Contacts on Android from Google Account
One of the easiest ways of exporting a backup of your contacts is through your Google account. You can export contacts on Android from your Google account no matter they were stored on your internal storage, SD card, or SIM card. But it’s worth mentioning that only you can export contacts from Google account if you have backed them up to Google before. The process is simple and foolproof, and here is how you can get started:
Open up the Google Contacts app on your phone.
Go to the menu on the left side. Click on Settings.
From Settings, go to the Export option.
Select which account you want to export from (if you have more than one).
The saved contacts file backup will be saved in the Downloads folder.
You can also save it in your Google Drive and can reference it later on.
2. Export Contacts in Samsung’s Contact App
If you use the Samsung Galaxy phone, then it is very simple and easy to export contacts as the phone has an in-built contacts app from where you can easily make a backup. To do this, you have to confirm that the contacts you want to export are still stored on your device: you can’t export a deleted or lost contact list by doing so. To begin, this is what you can do:
Step 1: After opening up the Contacts app, go to Menu in the upper corner.
Step 2: Select the Manage Contacts option.
Step 3: Select the Import/Export Contacts option and click on Export.
Step 4: Now the contacts backup can be saved in your internal storage.
Step 5: By navigating the internal storage through the My Files app, you will find the Contacts.vsf file.
Step 6: Now you can either upload it to your Google Drive, email it, or save it on your computer by the sharing options.
3. Export Contacts from Android through D-Back Android
Another method that will give you a safe and secure way to export your contacts from your Android phone is the D-Back Android software. It is one of the fastest methods to get all your existing and lost contacts retrieved from all nooks and corners of your phone, and then export them from Android to the computer. This is by far the easiest and reliable way to export contacts from Android.
You’re able to easily export contacts from Android to your computer.
You can easily export them to your PC from your Google backup without overwritting your current data on your device.
Simply exports or recovers contacts from Android by a few clicks, no tech knowledge required.
Helps you extract and export the existing and deleted contacts from Android.
Freely choose specific contacts to export, or export the whole contacts list.
You’re able to preview the contacts on your Android device before the export.
How to Export Contacts Stored on Android using D-Back Android:
Step 1. Download and launch D-Back for Android, choose a suitable recovery mode from «Android Data Recovery» and «Broken Android Data Extractor«.
Step 2. Select your device information: Device Name and Device Model, then the program will download suitable data package for your Android device.
Step 3. Use a USB cable to connect your Android device to your PC.
Step 4. Select the file type you want to export, «Contacts» in this case.
Step 5. After the scan finished, all the contacts will be displayed orderly overtime on the screen, choose the one you want to export, and click the «Recover» button. Then the contacts will be exported and saved on your PC.
Conclusion
We hope you found this article helpful on where are contacts stored on Android and how you can export them to have a safe backup. It is a good exercise to create a backup of your contacts because you would never know when you can lose them.
By Rosalin Tacita , to Undelete Android
Posted on Jul 06, 2020 ( Updated: Jul 24, 2020 )
Источник