Performing edit and add contact operation through menu button
<p>I have code where i am displaying the contacts through button action and  picking it display the name ,</p>

<p>After displaying when i press menu option i can get add, edit options. I am not able to perform there adding a contact its not showing any error nor its been added in the contacts.</p>

<p>In the edit i am not able to get how to refer the contact to edited which is being picked. Please suggest me, to edit the contact which is being picked please help me.
Here is the first code of display contacts.</p>

<pre><code>package com.visual.android;


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.view.View;

import android.widget.AdapterView;

import android.widget.ListView;

import android.widget.SimpleCursorAdapter;

import android.widget.AdapterView.OnItemClickListener;



public class ContactPicker extends Activity

 { 

@Override 

public void onCreate(Bundle icicle) 

{ 

super.onCreate(icicle); 

setContentView(R.layout.main); 



            Intent intent = getIntent(); 

            String dataPath = intent.getData().toString();



             final Uri data = Uri.parse(dataPath);

             final Cursor c = managedQuery(data, null, null, null, null);

             String[] from = new String[] {ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.Contacts.HAS_PHONE_NUMBER };



            int[] to = new int[] { R.id.itemTextView }; 

            SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.listitemlayout, c, from, to); 



            ListView lv = (ListView)findViewById(R.id.contactListView);

            lv.setAdapter(adapter); 

            lv.setOnItemClickListener(new OnItemClickListener() 

                { 

                    public void onItemClick(AdapterView&lt;?&gt; parent, View view, int pos, long id) 

                    {



                        int rowId = c.getInt(c.getColumnIndexOrThrow(ContactsContract.Contacts._ID));



                            Uri outURI = Uri.parse(data.toString() + "/" + rowId); 

                            Intent outData = new Intent(); 

                            outData.setData(outURI);


             setResult(Activity.RESULT_OK, outData);

             finish();

                    }

                });

        }

 } 
</code></pre>

<p>Here is the second code for displaying menu option and performing add and edit contact.</p>

<pre><code>package com.visual.android;


import java.util.ArrayList;

import java.util.Iterator;



import android.app.Activity;

import android.content.ContentProviderOperation;

import android.content.ContentProviderResult;

import android.content.ContentResolver;

import android.content.Context;

import android.content.Intent;

import android.content.OperationApplicationException;

import android.database.Cursor;

import android.net.Uri;

import android.os.Bundle;

import android.os.RemoteException;

import android.provider.ContactsContract;

import android.util.Log;

import android.view.Menu;

import android.view.MenuItem;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.ArrayAdapter;

import android.widget.Button;

import android.widget.EditText;

import android.widget.Spinner;

import android.widget.TextView;

import android.widget.Toast;



public class ContentPickerTester extends Activity



{

    public static Uri CONTENT_URI = Uri.parse("content://com.android.contacts/contacts");

    private Cursor cursor;

    Context c;



        private static final int MENU_ADD = Menu.FIRST; 

        private static final int MENU_EDIT = Menu.FIRST + 1;

        private static final int MENU_EXIT = Menu.FIRST + 2; 

        private static final int MENU_DELETE = Menu.FIRST + 3;

        private static final String TAG = "ContentPickerTester";



        private EditText mContactNameEditText; 

        private EditText mContactPhoneEditText; 

        private Button mContactSaveButton;

        private Spinner mContactPhoneTypeSpinner;

        private ArrayList&lt;Integer&gt; mContactPhoneTypes; 



    public boolean onCreateOptionsMenu(Menu menu) 

  {  



         menu.add(0, MENU_EDIT, 0, "EDIT").setIcon(android.R.drawable.ic_menu_edit);          

         menu.add(0, MENU_ADD, 0, "ADD NEW").setIcon(android.R.drawable.ic_menu_add);

         menu.add(0, MENU_DELETE, 0, "DELETE").setIcon(android.R.drawable.ic_menu_delete);

         menu.add(0, MENU_EXIT, 0, "EXIT").setIcon(android.R.drawable.ic_delete); 

         return super.onCreateOptionsMenu(menu);  

     }  



     public boolean onOptionsItemSelected(MenuItem item) 

     {  

         switch(item.getItemId()) 

         {  

              case MENU_ADD:  



                  Log.v(TAG, "Activity State: onCreate()");              

                  setContentView(R.layout.contact_adder); 



                  mContactNameEditText = (EditText) findViewById(R.id.contactNameEditText); 

                  mContactPhoneEditText = (EditText) findViewById(R.id.contactPhoneEditText);                 

                  mContactPhoneTypeSpinner = (Spinner) findViewById(R.id.contactPhoneTypeSpinner);                

                  mContactSaveButton = (Button) findViewById(R.id.contactSaveButton); 





                  mContactPhoneTypes = new ArrayList&lt;Integer&gt;(); 

                  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); 



                  ArrayAdapter&lt;String&gt; adapter; 

                  adapter = new ArrayAdapter&lt;String&gt;(this, android.R.layout.simple_spinner_item); 

                  adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 

                  Iterator&lt;Integer&gt; 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));                   

                  mContactSaveButton.setOnClickListener(new View.OnClickListener() { 



                      public void onClick(View v)

                      { 

                          onSaveButtonClicked(); 

                      } 



                      private void onSaveButtonClicked() { 

                          Log.v(TAG, "Save button clicked"); 

                          createContactEntry(); 



                      }   

                      private void createContactEntry() 



                      {

                  String name = mContactNameEditText.getText().toString(); 

                  String phone = mContactPhoneEditText.getText().toString(); 



                  int phoneType = mContactPhoneTypes.get( 

                          mContactPhoneTypeSpinner.getSelectedItemPosition()); 

                  try { 

                  ArrayList&lt;ContentProviderOperation&gt; ops = new ArrayList&lt;ContentProviderOperation&gt;(); 

                  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()); 



                  Log.i(TAG,"Creating contact: " + name); 



                      getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops); 





                  } 

                  catch (Exception e)

                  { 



                      Context ctx = getApplicationContext(); 

                      CharSequence txt = getString(R.string.contactCreationFailure); 

                      int duration = Toast.LENGTH_SHORT; 

                      Toast toast = Toast.makeText(ctx, txt, duration); 

                      toast.show(); 



                      Log.e(TAG, "Exception encountered while inserting contact: " + e); 

                  } 

              }

                  });


                                break;  

     case MENU_EDIT:


    Log.v(TAG, "Activity State: onCreate()");

                 setContentView(R.layout.editcontact); 

                String name = null;

                String phone = null;



                String nameSelected = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));   

                TextView tv = (TextView)findViewById(R.id.textView5); 

                tv.setText(nameSelected); 

                    ContentResolver cr = getContentResolver();



                    String where = ContactsContract.Data.DISPLAY_NAME + " = ? AND " + 

                                ContactsContract.Data.MIMETYPE + " = ? AND " +

                                String.valueOf(ContactsContract.CommonDataKinds.Phone.TYPE) + " = ? ";      

                    String[] params = new String[] {name,

                            ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,

                            String.valueOf(ContactsContract.CommonDataKinds.Phone.TYPE_HOME)};

                    Cursor phoneCur = managedQuery(ContactsContract.Data.CONTENT_URI, null, where, params, null);



                    ArrayList&lt;ContentProviderOperation&gt; ops = new ArrayList&lt;ContentProviderOperation&gt;();              

                    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) 

                            .build()); 


                                break;
case MENU_EXIT:

                        this.finish(); 

                    break;

                        }    

         return super.onOptionsItemSelected(item); 



            }  



                public static final int PICK_CONTACT = 1; 

                public void onCreate(Bundle icicle)

                                    {

        super.onCreate(icicle);

        setContentView(R.layout.contentpickertester); 

        Button button = (Button)findViewById(R.id.pick_contact_button); 

        button.setOnClickListener(new OnClickListener() 

        {

                public void onClick(View _view)

                {

                    Intent intent = new Intent(Intent.ACTION_PICK,Uri.parse("content://com.android.contacts/contacts"));

                    startActivityForResult(intent, PICK_CONTACT); 

                    }

            });

                                    } 



                public void onActivityResult(int reqCode, int resCode, Intent data) 

                { 

        super.onActivityResult(reqCode, resCode, data); 

        switch(reqCode)

        {

            case (PICK_CONTACT) : 

            { 

        if (resCode == Activity.RESULT_OK) 

        { 



            Uri contactData = data.getData();       

            Cursor c = managedQuery(contactData, null, null, null, null); 

            c.moveToFirst(); 

            Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;  

            String[] projection    = new String[] {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,                  

            ContactsContract.CommonDataKinds.Phone.NUMBER};    

            Cursor people = getContentResolver().query(uri, projection, null, null, null);    

            int indexName = people.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);  

            int indexNumber = people.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);    

            people.moveToFirst();  

        do {      


            String name   = people.getString(indexName);

            String number = people.getString(indexNumber);    

            } while (people.moveToNext()); 


            String name = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));     

            TextView tv = (TextView)findViewById(R.id.selected_contact_textview); 

            tv.setText(name); 



            }

            break;

            }

        } 

    }
}
</code></pre>
