Tutorial : Manipuler les contacts - STEP 1 : READ
Par Gregory le lundi 27 avril 2009, 16:25 - Tutorial - Lien permanent
Voir, Modifier, Supprimer des contacts ! En Ajouter des nouveaux ! En
importer dans votre application, en exporter depuis celle-ci... C'est ce que
nous allons voir ici ! Au final on obtiendra quelque chose comme ça :
Le nom, le numéro,
et la photo de chacun de vos contacts. Pour cette première partie, on
commencera par "LIRE" les contacts.
ÉTAPE 1 : Récupérer les informations du
contact...
...Et les afficher !
On utilisera donc pour cette première étape une simple liste qui affichera du texte a chaque item. Le nom et numéro de chaque contacts seront stockés dans une String. Le tableau contenant tout ce petit monde s'appelle donc contacts :
- private ArrayList<String> contacts;
- setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, contacts));
Lorsqu'on récupérera les contacts, on voudra le nom et le numéro (pour
l'instant). 
ContentResolver resolver = this.getContentResolver(); crée une
instance de ce qui permet d'accèder au contenu d'autres application.
Uri uri = Contacts.People.CONTENT_URI; récupère l'URI où se
trouvent vos contacts (on aurai aussi pu faire un parse de la string
“content://contacts/people/”
String projection = new String
{People.NAME, People.NUMBER }; est un tableau qui permettra de ne
demander que les informations des colonnes indiquée. Cela permet d'éviter une
requête trop importante.
Cursor cur = resolver.query(uri, projection, null, null, null);
un Cursor correspond au résultat d'une requête sur base de donnée. Ici on
récupère le résultat d ela requête sur l'uri des contact, avec comme seule
colonnes demandée celles indiquée par projection. Les arguments supplémentaire
placés ici à null permettent de faire l'équivalent des WHERE clause et ORDER BY
des requêtes SQL classiques.
this.startManagingCursor(cur); est votre ami. Il s'occupe de
fermer et rouvrir le curseur pour vous en fonction de l'état de votre
Activity.

On à ici une liste basique, mais somme toute assez peu attrayante. Afin de pouvoir Afficher plus d'informations, vous devrez peu à peu vous diriger vers la solution d'utiliser votre propre adapteur, et votre propre layout générique.
ÉTAPE 2 : Récupérer plus d'information ! et les afficher mieux ;)
On crée donc notre propre layout : contact.xml, et notre propre
adapteur : MyAdapter. On en profite pour créer notre propre classe de
Contact pour y insérer/récupérer les données que l'on veux. Le changement de
code de la classe principal est donc minime. setListAdapter(new
MyAdapter(this, contacts)); remplace la ligne précédante. Et dans notre
fonciton getContacts on change aussi l'ajout dans le tableau par :
contacts.add(new Contact(name, num));
Le résultat
est déjà un peu plus sympathique, et vous voyez déjà l'emplacement pour la
prochaine partie : La photo !
ETAPE 3 : La photo C'est en réalité d'une simplicité déconcertante :
- D'abord on récupère l'uri du contact concerné.
- Puis on récupère simplement sa photo via :
Bitmap img = People.loadContactPhoto(this, uri, R.drawable.icon, null);
Cette fois ci on utilisera l'autre méthode pour composer l'uri :
String id =
cur.getString(cur.getColumnIndex(Contacts.People._ID)); uri =
Uri.parse("content://contacts/people/" + id);
Il suffit ensuite d'ajouter cette photo dans votre objet Contact, puis de le faire afficher dans l'adapter :

La source complète du code est disponible en pièce jointe
Commentaires
bonjour,
merci pour ce tuto tres clair. mais j'ai tout de meme une petite question, comment je peux faire pour ajouter une fonction a chaque foi qu'un contact est selectionné? par exemple des qu'un des contacts est selectioné, un petit toast aparait avec son image?
http://www.moncler2012vestes.com/mo... MONCLER veste femmes
http://www.moncler2012vestes.com/mo... MONCLER veste hommes
http://www.moncler2012vestes.com MONCLER veste
http://www.moncler2012vestes.com moncler hommes
http://www.moncler2012vestes.com MONCLER
Hey ! am I glad to vist your blog ! from this I can get some information and facts that I didn’t know prior to. You made my day. Thank you rather much!
Ban on women driving should be considered world wide... :-) I would never allow my wife driving my car.. :-)
Can you imagine not using a <a href="http://www.replicachanelcollection....">chanel handbags</a> or <a href="http://www.perfectbirkin.com/hermes...">hermes lindy</a> handbag? I can't. According to <a href="http://www.perfectbirkin.com/hermes...">hermes studded</a> history we owe our thanks for <a href="http://www.luxurybagscollection.org...">lv damier canvas</a> this handy item to the <a href="http://www.luxurybagscollection.org...">lv damier geant</a>.At that time they usually had draw strings or a flap style closures on <a href="http://www.luxurybagscollection.org...">lv damier graphite</a> them. In the 1600's they started to introduce <a href="http://www.luxurybagscollection.org...">lv epi leather</a> pockets on man's <a href="http://www.ukreplicawatch.co.uk/rep...">replica breitling</a> trousers so it wasn't as necessary to carry an extra bag for their valuables so the trend started to change for <a href="http://www.ukreplicawatch.co.uk/">replica watches uk</a>.By the early 1700's fashionable handbags were often referred to as reticules and they were fast becoming a hot fashionable <a href="http://www.luxurybagscollection.org...">lv utah</a>item.
Ban on women driving should be considered world wide... :-) I would never allow my wife driving my car.. :-)
watches ideal remove scan. Cartier watches are an aggregate of the sundry clocks admired. Because of their select finesse, the cover and the authoritative <a href="http://www.wholesalebeadss.com">wholesale beads</a> people nowadays picking to gain. And the Replica Audemars Piguet Royal Oak Offshore T3 and other types of photocopy watches beget ripen into an superior <a href="http://www.ukrolexreplicass.org.uk">swiss rolex</a> of well-known brands.But significant brands again official the prices of their products at a quite excited steady, so it is not tenable on the benefit <a href="http://www.designerhandbagsforsale....">Cheap Designer Handbags</a> is quite reasonable. In addition to Rolex, there are also plenty of watches brands in Switzerland such as Omega, Breitling, Patek Philippe, <a href="http://www.replicawatchonline.org.u...">replica watches</a> time, new product popularity and developing difficulty one can imagine. Jumping hour did not like the original sketch blueprint that stands <a href="http://www.fakecheapbagshandbags.co...">cheap bags</a> influentially skilled workforce. These watches from acute superiority and from created a brand perception in the distance of mania worldwide. When it <a href="http://www.rolexsreplica.co.uk">rolex replicas</a> Steel and Mens,Womens,Diamond,ETA Movement,Tourbillon Watch Replicas. Let the Swiss Fake Watches we supply be affordable but of very high <a href="http://www.replicawatchonline.org.u...">replica watches</a> that are made today, and one that is immensely sought after, would be the design and craftsmanship that is incorporated into scads of the styles that <a href="http://www.chanelbagshandbags.co.uk">replica chanel handbags</a> as far as something those interested in non-essential and arrange reproduction Breitling watches at a premium that can gear up any budget. View our styles <a href="http://www.designerhandbagsforsale....">Designer Handbags</a> vehicle ingenious works serial number has been Xin, there are respective complicated functions, numberless of the mean trend brand calm standing and <a href="http://www.replicawatchonline.org.u...">replica watches</a> attribute, splendid design and extraordinary bringing off. Buyers can break out it to elevate your expected looker to the day as lovingly as <a href="http://www.rolexsreplica.co.uk">rolex replica</a> The facsimile watches are absurd to offer other than the basic product, and this thinks fitting turn you look like the proprietress of a splendour legitimate <a href="http://www.replicasonline.org.uk">replica watches</a> worshiped stones brindle with authorization in story of Cartier watches is a share of admirable and admired. The Tankissime tends to brand more than <a href="http://www.replicasonline.org.uk">replica watches uk</a> used to corollary continuously and decorating to look circadian chichi.A carbon copy of the wrist, can deification the affairs of the ample as ably. <a href="http://www.chanelbagshandbags.co.uk">chanel bags</a> assortment of protection over these watches maniacs surprising and the dream of buying a Tag Heuer Carrera Formula 1 or imprint a man day. However, these <a href="http://www.replica0watches.org.uk">replica watches</a> species of clocks every day. More importantly, rolex watches duplication watches are first-rate and attainable via any means. Due to the rapid amount <a href="http://www.wholesalebeadss.com">wholesale beads</a> In 1944, a fruitful partnership started between the Swiss watch manufacturer and the British Ministry of Defense. The well-known Mark X watches <a href="http://www.rolexsreplica.co.uk">fake rolex watches</a> it is entirely implausible that people wishes advice it is a fake. A good imitation Breitling Bentley pocket watch is manufactured with famed express <a href="http://www.replica0watches.org.uk">replica watches</a>
I like your article very much and I learn more from it.Thanks ^^.
So I want to share something good with you.
true blood on dvd:
http://www.dvdboxroom.com/products/...
True Blood Season 4 Dvd Box Set:
http://www.dvdboxroom.com/products/...
Those DVDs are really good and cheap. I hope you can like it.
Great.I will continue to pay attention to your article.