I wrote a code to get the contact name, phone number and image from Contacts and display it on the list in Android. It works fine, but takes longer to load. I tried using multithreading in some parts of the code. But the loading time does not decrease.
Here is the onCreate() method:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); lvDetail = (ListView) findViewById(R.id.listView1); fetchcontacts(); lvDetail.setAdapter(new MyBaseAdapter(context, myList)); }
Here is the code for extracting contacts:
private void fetchcontacts() { // TODO Auto-generated method stub Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.Contacts.DISPLAY_NAME + " ASC"); int count = cursor.getCount(); if (count > 0) { Toast.makeText(context, "count >0", Toast.LENGTH_SHORT).show(); while (cursor.moveToNext()) { String columnId = ContactsContract.Contacts._ID; int cursorIndex = cursor.getColumnIndex(columnId); String id = cursor.getString(cursorIndex); name = cursor.getString(cursor .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); Toast.makeText(context, "Toast 1", Toast.LENGTH_SHORT).show(); int numCount = Integer.parseInt(cursor.getString(cursor .getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))); if (numCount > 0) { Toast.makeText(context, "Toast 2", Toast.LENGTH_SHORT).show(); Cursor phoneCursor = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null, CommonDataKinds.Phone.CONTACT_ID+" = ?", new String[] { id }, ContactsContract.Contacts.DISPLAY_NAME + " ASC"); while (phoneCursor.moveToNext()) { Toast.makeText(context, "Toast 3", Toast.LENGTH_SHORT).show(); phoneNo = phoneCursor.getString(phoneCursor .getColumnIndex(ContactsContract.CommonDataKinds. Phone.NUMBER)); String image_uri = phoneCursor .getString(phoneCursor .getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI)); if (image_uri != null) { Toast.makeText(context, "Toast 4", Toast.LENGTH_SHORT).show(); System.out.println(Uri.parse(image_uri)); try { bitmap = MediaStore.Images.Media .getBitmap(this.getContentResolver(), Uri.parse(image_uri)); // sb.append("\n Image in Bitmap:" + bitmap); // System.out.println(bitmap); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } Toast.makeText(context, name, Toast.LENGTH_SHORT).show(); getDataInList(name,phoneNo,bitmap); name=null; phoneNo=null; Drawable myDrawable = getResources().getDrawable(R.drawable.star1); bitmap = ((BitmapDrawable) myDrawable).getBitmap(); } phoneCursor.close(); } } }
Here, the setAdapter () function in listview works after retrieving all the contacts in an ArrayList. Does anyone have an idea on how to display contacts while extracting contacts? any sample code?
android contacts android-contacts
irfan
source share