package com.eni.android.contact;

import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;

public class Ch11_ContactContentProviderAndroidActivity extends Activity {

	private static final String CONTACTS_LOADING = "Contacts Loading";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		final ContentResolver cr = getContentResolver();
		final Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
				null, null, null, ContactsContract.Contacts.DISPLAY_NAME
						+ " ASC");

		final int nameIndex = cur
				.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
		final int hasPhoneIndex = cur
				.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER);
		final int idIndex = cur.getColumnIndex(ContactsContract.Contacts._ID);

		while (cur.moveToNext()) {
			String name = cur.getString(nameIndex);
			String hasNumber = cur.getString(hasPhoneIndex);
			String id = cur.getString(idIndex);

			if (Integer.parseInt(hasNumber) > 0) {
				if (BuildConfig.DEBUG)
					Log.d(CONTACTS_LOADING, "Contact Name = " + name);
				final Cursor pCur = cr.query(
						ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
						null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID
								+ " = ?", new String[] { id }, null);
				final int numberIndex = pCur
						.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);

				while (pCur.moveToNext()) {
					String number = pCur.getString(numberIndex);
					if (BuildConfig.DEBUG)
						Log.d(CONTACTS_LOADING, "Contact Number  = " + number);
				}

				pCur.close();
			}

		}

		cur.close();

	}
}