Search code examples
androidandroid-contactsphone-number

How do you retrieve an ID from a phone number?


I am trying to retrieve Phone Number hence using

String addrWhere = Contacts.Phones.NUMBER + " = " + userNumber;
  String id = "";
  Cursor c = mContext.getContentResolver().query(
    Contacts.Phones.CONTENT_URI,
    new String[] { Contacts.Phones._ID }, addrWhere, null, null);
  try {
   if (c.getCount() > 0) {
    c.moveToFirst();
    id = c.getString(0);
    Log.i("IDS", id);
   }
  } finally {
   c.close();
  }
  return id;

Can anyone let me know my mistake in this?


Solution

  • HI Every one... thanks for reply!!! @ Sotapanna well i found the answer as pointed by Sotapanna

    pasting the working code for anyone who needs it!

    private String findID(String userNumber) {
            Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri
                    .encode(userNumber));
            int id = 0;
            String[] returnVals = new String[] { PhoneLookup._ID };
            Cursor pCur = mContext.getContentResolver().query(uri, returnVals,
                    PhoneLookup.NUMBER + " = \"" + userNumber + "\"", null, null);
            if (pCur.getCount() > 0) {
                pCur.moveToFirst();
                id = pCur.getColumnCount();
                if (id >= 0) {
                    id = pCur.getInt(0);
                }
            }
    
            Log.i("Contacts", "" + id);
            return String.valueOf(id);
        }