IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Android Discussion :

gestion de contacts


Sujet :

Android

  1. #1
    Nouveau Candidat au Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Juin 2014
    Messages
    1
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Maroc

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Juin 2014
    Messages : 1
    Points : 1
    Points
    1
    Par défaut gestion de contacts
    BBonjour 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éé:

    ContactAdder

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

  2. #2
    Expert confirmé
    Avatar de Hephaistos007
    Profil pro
    Enseignant Chercheur
    Inscrit en
    Décembre 2004
    Messages
    2 493
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations professionnelles :
    Activité : Enseignant Chercheur
    Secteur : Enseignement

    Informations forums :
    Inscription : Décembre 2004
    Messages : 2 493
    Points : 4 166
    Points
    4 166
    Par défaut
    A quel moment utilises-tu le ContentResolver dans ton code ?
    Il vaut mieux mobiliser son intelligence sur des conneries que mobiliser sa connerie sur des choses intelligentes --- devise SHADOKS

    Kit de survie Android : mon guide pour apprendre à programmer sur Android, mon tutoriel sur les web services et enfin l'outil en ligne pour vous faire gagner du temps - N'oubliez pas de consulter la FAQ Android

Discussions similaires

  1. [DC][Debutant]Gestion de contacts / Identification
    Par samyco dans le forum Diagrammes de Classes
    Réponses: 6
    Dernier message: 30/01/2008, 10h56
  2. Gestion de contacts
    Par lordelite dans le forum Pascal
    Réponses: 22
    Dernier message: 05/08/2007, 02h03
  3. Réponses: 6
    Dernier message: 01/03/2007, 09h43
  4. Gestion de contact
    Par matrxjean1984 dans le forum Autres Logiciels
    Réponses: 4
    Dernier message: 23/03/2006, 21h24

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo