通讯录 实现简单查询

 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();
    }
   }
  });
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值