PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, November 6, 2022

[FIXED] How to Delete phone number from contact in android?

 November 06, 2022     android, android-cursor, contacts     No comments   

Issue

I want to delete (e.g. mobile number) from android database. For that I am passing query as follow

public class ContactDemo extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        String number = "2222";
        Long id = getID(number);
        int i = getContentResolver().delete(RawContacts.CONTENT_URI, RawContacts._ID+"=?", new String[]{id.toString()});
       System.out.println("Deleted"+i);
    }
    public Long getID(String number){       

        Uri uri =  Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
        Cursor c =  getContentResolver().query(uri, new String[]{PhoneLookup._ID}, null, null, null);
        while(c.moveToNext()){
            return c.getLong(c.getColumnIndex(PhoneLookup._ID));
        }
        return null;
    }    
}

but it is deleting entire contact.

What should I use to delete only that phone number (not entire contact)?


Solution

You use the delete method of the ContentResolver so you delete the whole contact. To update the phone number of this contact to an empty value, you need to use the ContactsContact API.

http://developer.android.com/reference/android/provider/ContactsContract.Data.html

By providing the contact raw id and a Phone.CONTENT_ITEM_TYPE, you can request only for phone number belonging to this contact and then remove all of them.

 ArrayList<ContentProviderOperation> ops = Lists.newArrayList();
 ops.add(ContentProviderOperation.newDelete(Data.CONTENT_URI)
          .withSelection(Data._ID + "=? and " + Data.MIMETYPE + "=?", new String[]{String.valueOf(contactId), Phone.CONTENT_ITEM_TYPE})
          .build());
 getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);


Answered By - Moystard
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing