package cn.wy;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private EditText edit1;
private EditText edit2;
private EditText edit3;
private Button button;
private ContentResolver contentResolver;
private String phone;
private String email;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
edit1 = (EditText) this.findViewById(R.id.edit1);
edit2 = (EditText) this.findViewById(R.id.edit2);
edit3 = (EditText) this.findViewById(R.id.edit3);
button = (Button) this.findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//这是访问通讯录所有信息的固定地址
Uri uri = Uri.parse("content://com.android.contacts/contacts");
contentResolver = MainActivity.this.getContentResolver();
Cursor c = contentResolver.query(uri, null, null, null, null);
//循环、当游标指向下一个主键_id(一个主键_id就是一个存入的联系人)
StringBuffer sb = new StringBuffer();
String name = null;
while(c.moveToNext()) {
//这是查的raw_contacts表,该表提供了主键"_id"和"display_name"
int id = c.getInt(c.getColumnIndex("_id"));
name = c.getString(c.getColumnIndex("display_name"));
sb.append(name);
//查询data表下当前联系人的电话号码,条件是外键"contack_id"等于?
uri = Uri.parse("content://com.android.contacts/data/phones");
Cursor phoneCursor = contentResolver.query(uri, null, "contact_id=?", new String[]{String.valueOf(id)}, null);
while(phoneCursor.moveToNext()) {
phone = phoneCursor.getString(phoneCursor.getColumnIndex("data1"));
}
//查询data表下当前联系人的email,条件还是外键"contack_id"等于?
uri = Uri.parse("content://com.android.contacts/data/emails");
Cursor emailCursor = contentResolver.query(uri, null, "contact_id=?", new String[]{String.valueOf(id)}, null);
while(emailCursor.moveToNext()) {
email = emailCursor.getString(emailCursor.getColumnIndex("data1"));
}
if(edit1.getText().toString().equals(name)) {
edit2.setText(phone);
edit3.setText(email);
}
}
Log.i("tag",sb.toString() );
if(sb.toString().contains(edit1.getText().toString())==false) {
Toast.makeText(MainActivity.this, "通讯录无此记录", Toast.LENGTH_LONG).show();
}
}
});
}
}