package com.example.phonelist;

import android.app.Activity;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class PhoneEditActivity extends Activity {
  TextView contactName;
  EditText phoneText;
  long id;
  
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_phone_edit);
    id = getIntent().getLongExtra("id", 0);
    Cursor c = getContentResolver().query(
        ContentUris.withAppendedId(
            ContactsContract.CommonDataKinds.Phone.CONTENT_URI, id),
            null, null, null, null);
    contactName = (TextView)findViewById(R.id.contactName);
    phoneText = (EditText)findViewById(R.id.phoneText);
    if (c.moveToFirst()) {
      contactName.setText(c.getString(
          c.getColumnIndex(
              ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)));
      phoneText.setText(c.getString(
          c.getColumnIndex(
              ContactsContract.CommonDataKinds.Phone.NUMBER)));
    }
    
    Button saveButton = (Button)findViewById(R.id.saveButton);
    saveButton.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        String number = phoneText.getText().toString();
        ContentValues cv = new ContentValues();
        cv.put(ContactsContract.CommonDataKinds.Phone.NUMBER, number);
        getContentResolver().update(ContentUris.withAppendedId(
            ContactsContract.CommonDataKinds.Phone.CONTENT_URI, id),
            cv, null, null);
        PhoneEditActivity.this.finish();
      }     
    });
  }

}
