M.Movaffagh
M.Movaffagh

Reputation: 1312

How to delete a Contact in Android 2.2 with name ?

I want to delete A Contact with special name.

I try below code to find my target :

public Cursor searchByName(String name)
    {
        try
        {
            ContentResolver cr = getContentResolver();
            Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
            if (cur.getCount() > 0) 
            {
                while (cur.moveToNext()) 
                {
                    //String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
                    String Name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                    if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) 
                    {
                        if(Name.equals(name))
                        {
                            return cur; 
                        }
                    }
                }
            }
        }
        catch (Exception e) 
        {
            Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
        }
        return null;
    }

and below Function to remove it :

public void removeContactByName(String name)
{
    try
    {
        Cursor cur = searchByName(name);
        if(cur!=null)
        {
            Uri uri ; // what should it be?
            getContentResolver().delete(uri,null, null);
        }
        else
        {
            Toast.makeText(getApplicationContext(), "Not Found",Toast.LENGTH_SHORT).show();
        }
    }
    catch (Exception e) 
    {
        Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
    }
} 

but what should uri be?

Upvotes: 2

Views: 726

Answers (1)

Mohammad Ersan
Mohammad Ersan

Reputation: 12444

you can search for the Contact by name, and get it _id, after that, delete it by _id

Upvotes: 1

Related Questions