package com.example.phonelist;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class PhoneListActivity extends ListActivity {
  private SimpleCursorAdapter sca;
  private Cursor cursor;
  private Context context;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    context = this;
    Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
    String[] projection = new String[] {
        ContactsContract.CommonDataKinds.Phone._ID,
        ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
        ContactsContract.CommonDataKinds.Phone.NUMBER,
        ContactsContract.CommonDataKinds.Phone.TYPE,
    };
    String orderBy = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME;

    cursor = getContentResolver().query(uri, projection, null, null, orderBy);
    startManagingCursor(cursor);
    String[] columns = new String[] {
        projection[1],
        projection[2]
    };
    int[] views = new int[] { R.id.nameView, R.id.numberView, };
    sca = new SimpleCursorAdapter(context, R.layout.activity_phone_list,
        cursor, columns, views, 0);
    setListAdapter(sca);
  }

  @Override
  protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);
    Intent i = new Intent(PhoneListActivity.this, PhoneEditActivity.class);
    i.putExtra("id", id);
    startActivity(i);
  }

}
