Android examples for Account:Contact Name
find Contact Name by number
/*/*from w ww.ja va 2s . co m*/ * Copyright 2013 Luke Klinker * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ //package com.java2s; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.provider.ContactsContract; import android.telephony.PhoneNumberUtils; import android.text.Editable; import android.text.SpannableStringBuilder; import java.util.Locale; public class Main { public static String findContactName(String number, Context context) { try { String name = ""; String origin = number; if (origin.length() != 0) { Uri phoneUri = Uri.withAppendedPath( ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(origin)); Cursor phonesCursor = context .getContentResolver() .query(phoneUri, new String[] { ContactsContract.Contacts.DISPLAY_NAME_PRIMARY, ContactsContract.RawContacts._ID }, null, null, ContactsContract.Contacts.DISPLAY_NAME + " desc limit 1"); try { if (phonesCursor != null && phonesCursor.moveToFirst()) { name = phonesCursor.getString(0); } else { if (!number.equals("")) { try { Locale sCachedLocale = Locale.getDefault(); int sFormatType = PhoneNumberUtils .getFormatTypeForLocale(sCachedLocale); Editable editable = new SpannableStringBuilder( number); PhoneNumberUtils.formatNumber(editable, sFormatType); name = editable.toString(); } catch (Exception e) { name = number; } } else { name = "No Information"; } } } finally { phonesCursor.close(); } } else { if (!number.equals("")) { try { Long.parseLong(number.replaceAll("[^0-9]", "")); Locale sCachedLocale = Locale.getDefault(); int sFormatType = PhoneNumberUtils .getFormatTypeForLocale(sCachedLocale); Editable editable = new SpannableStringBuilder( number); PhoneNumberUtils .formatNumber(editable, sFormatType); name = editable.toString(); } catch (Exception e) { name = number; } } else { name = "No Information"; } } return name; } catch (Exception e) { // something weird when looking up the number I think (mms tokens sometimes give a weird initial number instead of phone number) return number; } } }