get Contact List and return a Map - Android Account

Android examples for Account:Contact Get

Description

get Contact List and return a Map

Demo Code


import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.telephony.TelephonyManager;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class Main{
    public static Map getContactList(Context context) {
        String zip = "+" + GetCountryZipCode(context);
        Cursor phones = context.getContentResolver().query(
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                null, null, null);/*  ww  w  . jav  a  2 s  .c om*/
        Map<String, String> countMap = new HashMap<String, String>();
        while (phones.moveToNext()) {
            String name = phones
                    .getString(phones
                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            String phoneNumber = phones
                    .getString(phones
                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

            if (phoneNumber.startsWith("0")) {
                String codeNumber = zip + phoneNumber.substring(1);
                phoneNumber = codeNumber.replaceAll("\\s", "");
            }

            countMap.put(phoneNumber, name);
        }
        phones.close();

        return countMap;
    }
    public static String GetCountryZipCode(Context context) {
        String CountryID = "";
        String CountryZipCode = "";

        TelephonyManager manager = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        CountryID = manager.getSimCountryIso().toUpperCase();
        String[] rl = context.getResources().getStringArray(
                R.array.CountryCodes);
        for (int i = 0; i < rl.length; i++) {
            String[] g = rl[i].split(",");
            if (g[1].trim().equals(CountryID.trim())) {
                CountryZipCode = g[0];
                break;
            }
        }
        return CountryZipCode;
    }
}

Related Tutorials