0

I am trying to get the phone contacts and store it in a Hashmap. I want to save that locally and use it anywhere in the project. Following is my code to get phone contacts:

public HashMap getPhoneContacts() {

    ArrayList contactList=null;
    ContentResolver cr = getContext().getContentResolver(); //Activity/Application android.content.Context
    Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null
            , null, null, null);
    if(cursor.moveToFirst())
    {
        contactList = new ArrayList<String>();
        do
        {
            String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            String contactName=cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

            if(Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
            {
                Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",new String[]{ id }, null);
                while (pCur.moveToNext())
                {
                    String contactNumber = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    //String contactId = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    String noramliseNum;
                    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                        noramliseNum = PhoneNumberUtils.normalizeNumber(contactNumber);
                    }else{
                        noramliseNum=contactNumber.replaceAll("\\s","");
                    }
                    phoneContacts.put(noramliseNum,contactName);
                    break;
                }
                pCur.close();
            }

        } while (cursor.moveToNext()) ;
    }

    return phoneContacts;
}

Its already taking lot of time to fetch all the contacts. So I dont want to call this function again and again from other classes. Instead I need to call the function only once,and then store it in a Hashmap locally and use it whenever we want,so that it wont take time to fetch the details again.

Please help.

Banana
  • 2,435
  • 7
  • 34
  • 60
neab
  • 91
  • 1
  • 3
  • 10

2 Answers2

0

You could put it into SharedPreferences if you don't want to re-download every time you start the app. Then, once the data is retreived, you could have a Singleton class to hold your Hashmap.

Lance Toth
  • 430
  • 3
  • 17
0

If you have many contacts, you should consider using a database.

Take a look at https://developer.android.com/guide/topics/data/data-storage.html

This would be more efficient than keeping everything in memory.

olikaf
  • 591
  • 3
  • 11