package com.example.mycontacts;

import android.os.Bundle;
import android.provider.ContactsContract;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends Activity {
	TextView txt;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		txt = (TextView)findViewById(R.id.text1);
	}
	
	public void getEmails(View v) {
		String emails = getEmailData();
		txt.setText(emails);
	}
	
	private String getEmailData() {
		String emails = "";
		try {
			ContentResolver cr = getBaseContext().getContentResolver();
			Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
			if (cursor.getCount()>0) {
				Log.i("Content Provider", "Reading Contacts Emails");
				while (cursor.moveToNext()) {
					String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
					Cursor emaildata = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                            null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contactId, null, null);
					while (emaildata.moveToNext()) {
						String emailAddress = emaildata.getString(emaildata.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
						emails +="\n"+emailAddress+"\n"+"--------------------------------------";
					}
					emaildata.close();
				}
			}
			else {
				emails +="\nData not found.\n";
			}
			cursor.close();
		}
		catch (Exception e) {
			emails +="Exception : "+e+"";
		}
		return emails;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}
