Résolu gestion de contacts

Solutions (2)
Tags :
  • Applications mobiles
  • Applications Android
  • Android
  • Applications
, Zombie |
Bonjour je suis sur le point de crée un application pour la gestion de contacts sous android j'ai déjà crée l’interface et les classes qu'elle en'a besoin, mais le bouton enregistrer ne marche pas c a d je n'arrive pas a enregistrer et en plus je peux pas visualiser les détails de chaque contact si quelqu’un peux m'aider voila les classes que j'ai créé:

Contact Adder

  1. package com.example.android.contactmanager;
  2.  
  3. import android.accounts.Account;
  4. import android.accounts.AccountManager;
  5. import android.accounts.AuthenticatorDescription;
  6. import android.accounts.OnAccountsUpdateListener;
  7. import android.app.Activity;
  8. import android.content.ContentProviderOperation;
  9. import android.content.Context;
  10. import android.content.pm.PackageManager;
  11. import android.graphics.drawable.Drawable;
  12. import android.os.Bundle;
  13. import android.provider.ContactsContract;
  14. import android.util.Log;
  15. import android.view.LayoutInflater;
  16. import android.view.View;
  17. import android.view.ViewGroup;
  18. import android.widget.AdapterView;
  19. import android.widget.ArrayAdapter;
  20. import android.widget.Button;
  21. import android.widget.EditText;
  22. import android.widget.ImageView;
  23. import android.widget.Spinner;
  24. import android.widget.TextView;
  25. import android.widget.Toast;
  26. import android.widget.AdapterView.OnItemSelectedListener;
  27.  
  28. import java.util.ArrayList;
  29. import java.util.Iterator;
  30.  
  31. public final class ContactAdder extends Activity implements OnAccountsUpdateListener
  32. {
  33. public static final String TAG = "ContactsAdder";
  34. public static final String ACCOUNT_NAME =
  35. "com.example.android.contactmanager.ContactsAdder.ACCOUNT_NAME";
  36. public static final String ACCOUNT_TYPE =
  37. "com.example.android.contactmanager.ContactsAdder.ACCOUNT_TYPE";
  38.  
  39. private ArrayList<AccountData> mAccounts;
  40. private AccountAdapter mAccountAdapter;
  41. private Spinner mAccountSpinner;
  42. private EditText mContactEmailEditText;
  43. private EditText mContactNameEditText;
  44. private EditText mContactPhoneEditText;
  45. private ArrayList<Integer> mContactPhoneTypes;
  46. private Spinner mContactPhoneTypeSpinner;
  47. private Button mContactSaveButton;
  48. private AccountData mSelectedAccount;
  49.  
  50. /**
  51.   * Called when the activity is first created. Responsible for initializing the UI.
  52.   */
  53. /**/
  54. @Override
  55. public void onCreate(Bundle savedInstanceState)
  56. {
  57. Log.v(TAG, "Activity State: onCreate()");
  58. super.onCreate(savedInstanceState);
  59. setContentView(R.layout.contact_adder);
  60.  
  61. // Obtain handles to UI objects
  62. mAccountSpinner = (Spinner) findViewById(R.id.accountSpinner);
  63. mContactNameEditText = (EditText) findViewById(R.id.contactNameEditText);
  64. mContactPhoneEditText = (EditText) findViewById(R.id.contactPhoneEditText);
  65. mContactEmailEditText = (EditText) findViewById(R.id.contactEmailEditText);
  66. mContactPhoneTypeSpinner = (Spinner) findViewById(R.id.contactPhoneTypeSpinner);
  67. mContactSaveButton = (Button) findViewById(R.id.contactSaveButton);
  68.  
  69. // Prepare list of supported account types
  70. // Note: Other types are available in ContactsContract.CommonDataKinds
  71. // Also, be aware that type IDs differ between Phone.
  72. mContactPhoneTypes = new ArrayList<Integer>();
  73. mContactPhoneTypes.add(ContactsContract.CommonDataKinds.Phone.TYPE_HOME);
  74. mContactPhoneTypes.add(ContactsContract.CommonDataKinds.Phone.TYPE_WORK);
  75. mContactPhoneTypes.add(ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE);
  76. mContactPhoneTypes.add(ContactsContract.CommonDataKinds.Phone.TYPE_OTHER);
  77.  
  78. // Prepare model for account spinner
  79. mAccounts = new ArrayList<AccountData>();
  80. mAccountAdapter = new AccountAdapter(this, mAccounts);
  81. mAccountSpinner.setAdapter(mAccountAdapter);
  82.  
  83. // Populate list of account types for phone
  84. ArrayAdapter<String> adapter;
  85. adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
  86. adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
  87. Iterator<Integer> iter;
  88. iter = mContactPhoneTypes.iterator();
  89. while (iter.hasNext()) {
  90. adapter.add(ContactsContract.CommonDataKinds.Phone.getTypeLabel(
  91. this.getResources(),
  92. iter.next(),
  93. getString(R.string.undefinedTypeLabel)).toString());
  94. }
  95. mContactPhoneTypeSpinner.setAdapter(adapter);
  96. mContactPhoneTypeSpinner.setPrompt(getString(R.string.selectLabel));
  97.  
  98.  
  99. // Prepare the system account manager. On registering the listener below, we also ask for
  100. // an initial callback to pre-populate the account list.
  101. AccountManager.get(this).addOnAccountsUpdatedListener(this, null, true);
  102.  
  103. // Register handlers for UI elements
  104. mAccountSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
  105. public void onItemSelected(AdapterView<?> parent, View view, int position, long i) {
  106. updateAccountSelection();
  107. }
  108.  
  109. public void onNothingSelected(AdapterView<?> parent) {
  110. // We don't need to worry about nothing being selected, since Spinners don't allow
  111. // this.
  112. }
  113. });
  114. mContactSaveButton.setOnClickListener(new View.OnClickListener() {
  115. public void onClick(View v) {
  116. onSaveButtonClicked();
  117. }
  118. });
  119. }
  120.  
  121. /**
  122.   * Actions for when the Save button is clicked. Creates a contact entry and terminates the
  123.   * activity.
  124.   */
  125. private void onSaveButtonClicked() {
  126. Log.v(TAG, "Save button clicked");
  127. createContactEntry();
  128. finish();
  129. }
  130.  
  131. /**
  132.   * Creates a contact entry from the current UI values in the account named by mSelectedAccount.
  133.   */
  134. protected void createContactEntry() {
  135. // Get values from UI
  136. String name = mContactNameEditText.getText().toString();
  137. String phone = mContactPhoneEditText.getText().toString();
  138. String email = mContactEmailEditText.getText().toString();
  139. int phoneType = mContactPhoneTypes.get(
  140. mContactPhoneTypeSpinner.getSelectedItemPosition());
  141.  
  142. // Prepare contact creation request
  143. //
  144. // Note: We use RawContacts because this data must be associated with a particular account.
  145. // The system will aggregate this with any other data for this contact and create a
  146. // coresponding entry in the ContactsContract.Contacts provider for us.
  147. ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
  148. ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
  149. .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, mSelectedAccount.getType())
  150. .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, mSelectedAccount.getName())
  151. .build());
  152. ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
  153. .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
  154. .withValue(ContactsContract.Data.MIMETYPE,
  155. ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
  156. .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, name)
  157. .build());
  158. ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
  159. .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
  160. .withValue(ContactsContract.Data.MIMETYPE,
  161. ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
  162. .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, phone)
  163. .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, phoneType)
  164. .build());
  165. ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
  166. .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
  167. .withValue(ContactsContract.Data.MIMETYPE,
  168. ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
  169. .withValue(ContactsContract.CommonDataKinds.Email.DATA, email)
  170. // .withValue(ContactsContract.CommonDataKinds.Email.TYPE, emailType)
  171. .build());
  172.  
  173. // Ask the Contact provider to create a new contact
  174. Log.i(TAG,"Selected account: " + mSelectedAccount.getName() + " (" +
  175. mSelectedAccount.getType() + ")");
  176. Log.i(TAG,"Creating contact: " + name);
  177. try {
  178. getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
  179. } catch (Exception e) {
  180. // Display warning
  181. Context ctx = getApplicationContext();
  182. CharSequence txt = getString(R.string.contactCreationFailure);
  183. int duration = Toast.LENGTH_SHORT;
  184. Toast toast = Toast.makeText(ctx, txt, duration);
  185. toast.show();
  186.  
  187. // Log exception
  188. Log.e(TAG, "Exceptoin encoutered while inserting contact: " + e);
  189. }
  190. }
  191.  
  192. /**
  193.   * Called when this activity is about to be destroyed by the system.
  194.   */
  195. @Override
  196. public void onDestroy() {
  197. // Remove AccountManager callback
  198. AccountManager.get(this).removeOnAccountsUpdatedListener(this);
  199. super.onDestroy();
  200. }
  201.  
  202. /**
  203.   * Updates account list spinner when the list of Accounts on the system changes. Satisfies
  204.   * OnAccountsUpdateListener implementation.
  205.   */
  206. public void onAccountsUpdated(Account[] a) {
  207. Log.i(TAG, "Account list update detected");
  208. // Clear out any old data to prevent duplicates
  209. mAccounts.clear();
  210.  
  211. // Get account data from system
  212. AuthenticatorDescription[] accountTypes = AccountManager.get(this).getAuthenticatorTypes();
  213.  
  214. // Populate tables
  215. for (int i = 0; i < a.length; i++) {
  216. // The user may have multiple accounts with the same name, so we need to construct
  217. // meaningful display name for each.
  218. String systemAccountType = a[i].type;
  219. AuthenticatorDescription ad = getAuthenticatorDescription(systemAccountType,
  220. accountTypes);
  221. AccountData data = new AccountData(a[i].name, ad);
  222. mAccounts.add(data);
  223. }
  224.  
  225. // Update the account spinner
  226. mAccountAdapter.notifyDataSetChanged();
  227. }
  228.  
  229. /**
  230.   * Obtain the AuthenticatorDescription for a given account type.
  231.   * @param type The account type to locate.
  232.   * @param dictionary An array of AuthenticatorDescriptions, as returned by AccountManager.
  233.   * @return The description for the specified account type.
  234.   */
  235. private static AuthenticatorDescription getAuthenticatorDescription(String type,
  236. AuthenticatorDescription[] dictionary) {
  237. for (int i = 0; i < dictionary.length; i++) {
  238. if (dictionary[i].type.equals(type)) {
  239. return dictionary[i];
  240. }
  241. }
  242. // No match found
  243. throw new RuntimeException("Unable to find matching authenticator");
  244. }
  245.  
  246. /**
  247.   * Update account selection. If NO_ACCOUNT is selected, then we prohibit inserting new contacts.
  248.   */
  249. private void updateAccountSelection() {
  250. // Read current account selection
  251. mSelectedAccount = (AccountData) mAccountSpinner.getSelectedItem();
  252. }
  253.  
  254. /**
  255.   * A container class used to repreresent all known information about an account.
  256.   */
  257. private class AccountData {
  258. private String mName;
  259. private String mType;
  260. private CharSequence mTypeLabel;
  261. private Drawable mIcon;
  262.  
  263. /**
  264.   * @param name The name of the account. This is usually the user's email address or
  265.   * username.
  266.   * @param description The description for this account. This will be dictated by the
  267.   * type of account returned, and can be obtained from the system AccountManager.
  268.   */
  269. public AccountData(String name, AuthenticatorDescription description) {
  270. mName = name;
  271. if (description != null) {
  272. mType = description.type;
  273.  
  274. // The type string is stored in a resource, so we need to convert it into something
  275. // human readable.
  276. String packageName = description.packageName;
  277. PackageManager pm = getPackageManager();
  278.  
  279. if (description.labelId != 0) {
  280. mTypeLabel = pm.getText(packageName, description.labelId, null);
  281. if (mTypeLabel == null) {
  282. throw new IllegalArgumentException("LabelID provided, but label not found");
  283. }
  284. } else {
  285. mTypeLabel = "";
  286. }
  287.  
  288. if (description.iconId != 0) {
  289. mIcon = pm.getDrawable(packageName, description.iconId, null);
  290. if (mIcon == null) {
  291. throw new IllegalArgumentException("IconID provided, but drawable not " +
  292. "found");
  293. }
  294. } else {
  295. mIcon = getResources().getDrawable(android.R.drawable.sym_def_app_icon);
  296. }
  297. }
  298. }
  299.  
  300. public String getName() {
  301. return mName;
  302. }
  303.  
  304. public String getType() {
  305. return mType;
  306. }
  307.  
  308. public CharSequence getTypeLabel() {
  309. return mTypeLabel;
  310. }
  311.  
  312. public Drawable getIcon() {
  313. return mIcon;
  314. }
  315.  
  316. public String toString() {
  317. return mName;
  318. }
  319. }
  320.  
  321. /**
  322.   * Custom adapter used to display account icons and descriptions in the account spinner.
  323.   */
  324. private class AccountAdapter extends ArrayAdapter<AccountData> {
  325. public AccountAdapter(Context context, ArrayList<AccountData> accountData) {
  326. super(context, android.R.layout.simple_spinner_item, accountData);
  327. setDropDownViewResource(R.layout.account_entry);
  328. }
  329.  
  330. public View getDropDownView(int position, View convertView, ViewGroup parent) {
  331. // Inflate a view template
  332. if (convertView == null) {
  333. LayoutInflater layoutInflater = getLayoutInflater();
  334. convertView = layoutInflater.inflate(R.layout.account_entry, parent, false);
  335. }
  336. TextView firstAccountLine = (TextView) convertView.findViewById(R.id.firstAccountLine);
  337. TextView secondAccountLine = (TextView) convertView.findViewById(R.id.secondAccountLine);
  338. ImageView accountIcon = (ImageView) convertView.findViewById(R.id.accountIcon);
  339.  
  340. // Populate template
  341. AccountData data = getItem(position);
  342. firstAccountLine.setText(data.getName());
  343. secondAccountLine.setText(data.getTypeLabel());
  344. Drawable icon = data.getIcon();
  345. if (icon == null) {
  346. icon = getResources().getDrawable(android.R.drawable.ic_menu_search);
  347. }
  348. accountIcon.setImageDrawable(icon);
  349. return convertView;
  350. }
  351. }
  352. }


Et la classe ContactManager

  1. package com.example.android.contactmanager;
  2.  
  3. import android.app.Activity;
  4. import android.content.Intent;
  5. import android.database.Cursor;
  6. import android.net.Uri;
  7. import android.os.Bundle;
  8. import android.provider.ContactsContract;
  9. import android.util.Log;
  10. import android.view.View;
  11. import android.widget.Button;
  12. import android.widget.ListView;
  13. import android.widget.SimpleCursorAdapter;
  14.  
  15. public final class ContactManager extends Activity
  16. {
  17.  
  18. public static final String TAG = "ContactManager";
  19.  
  20. private Button mAddAccountButton;
  21. private ListView mContactList;
  22. private boolean mShowInvisible;
  23.  
  24.  
  25. /**
  26.   * Called when the activity is first created. Responsible for initializing the UI.
  27.   */
  28. @Override
  29. public void onCreate(Bundle savedInstanceState)
  30. {
  31. Log.v(TAG, "Activity State: onCreate()");
  32. super.onCreate(savedInstanceState);
  33. setContentView(R.layout.contact_manager);
  34.  
  35. // Obtain handles to UI objects
  36. mAddAccountButton = (Button) findViewById(R.id.addContactButton);
  37. mContactList = (ListView) findViewById(R.id.contactList);
  38.  
  39. // Initialize class properties
  40. mShowInvisible = false;
  41.  
  42. // Register handler for UI elements
  43. mAddAccountButton.setOnClickListener(new View.OnClickListener() {
  44. public void onClick(View v) {
  45. Log.d(TAG, "mAddAccountButton clicked");
  46. launchContactAdder();
  47. }
  48. });
  49.  
  50. // Populate the contact list
  51. populateContactList();
  52. }
  53.  
  54. /**
  55.   * Populate the contact list based on account currently selected in the account spinner.
  56.   */
  57. private void populateContactList() {
  58. // Build adapter with contact entries
  59. Cursor cursor = getContacts();
  60. String[] fields = new String[] {
  61. ContactsContract.Data.DISPLAY_NAME
  62. };
  63. SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.contact_entry, cursor,
  64. fields, new int[] {R.id.contactEntryText});
  65. mContactList.setAdapter(adapter);
  66. }
  67.  
  68. /**
  69.   * Obtains the contact list for the currently selected account.
  70.   *
  71.   * @return A cursor for for accessing the contact list.
  72.   */
  73. private Cursor getContacts()
  74. {
  75. // Run query
  76. Uri uri = ContactsContract.Contacts.CONTENT_URI;
  77. String[] projection = new String[] {
  78. ContactsContract.Contacts._ID,
  79. ContactsContract.Contacts.DISPLAY_NAME
  80. };
  81. String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '" +
  82. (mShowInvisible ? "0" : "1") + "'";
  83. String[] selectionArgs = null;
  84. String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
  85.  
  86. return managedQuery(uri, projection, selection, selectionArgs, sortOrder);
  87. }
  88.  
  89. /**
  90.   * Launches the ContactAdder activity to add a new contact to the selected accont.
  91.   */
  92. protected void launchContactAdder() {
  93. Intent i = new Intent(this, ContactAdder.class);
  94. startActivity(i);
  95. }
  96. }
  • elvally a édité ce message
  • OmaR a édité ce message
  • elvally a édité ce message
Contenus similaires
Meilleure solution
partage
|
Salut,

D'abord, peux-tu mettre ton code dan un tag [ code ]? parce que comme ça, ça donne pas envie de lire, alors je ne lis pas. :) 

De toutes façons, il est fort probable que ton problème vienne du fait que tu ais oublié d'ajouter les droits sur l'accès aux contacts dans le fichier Manifest (l'erreur classique et récurrente). Je me trompe ? ;) 
  • elvally a sélectionné cette solution comme la meilleure réponse
  • CRicky a édité ce message
  • Commenter cette solution |
Score
0
òh
òi
, Hardware (collector) |
salut,
c'est ce genre de application que tu cherche http://www.wondershare.fr/mobile-phone/gestionnaire-con...
  • Commenter cette réponse |

Ce n'est pas ce que vous cherchiez ?

Tom's guide dans le monde
  • Allemagne
  • Italie
  • Irlande
  • Royaume Uni
  • Etats Unis
Suivre Tom's Guide
Inscrivez-vous à la Newsletter
  • ajouter à twitter
  • ajouter à facebook
  • ajouter un flux RSS