获取手机通讯录信息示例

非常简单的的一个Demo示例直接上Java代码如下:

public class MainActivity extends Activity {
   
   private String uri_raw = "content://com.android.contacts/raw_contacts";
   private String uri_phone = "content://com.android.contacts/data/phones";   
   private ListView listView  = null;
   private TextView empty    = null;
   private ContentResolver contentResolver; 
   private List, String>> data = new ArrayList,String>>();
   private SimpleAdapter adapter;
   
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      
      listView= (ListView) findViewById(R.id.lv);
      empty = (TextView) findViewById(R.id.empty);
      listView.setEmptyView(empty);  
      adapter = new SimpleAdapter(this, data, R.layout.item, 
            new String[]{"_id","display_Name","data1"}, new int []{R.id.id,R.id.name,R.id.number});    
      listView.setAdapter(adapter);    
      contentResolver = getContentResolver(); //赋值  不要导v4
      reloadListView();
   }
   private void reloadListView() {
      // TODO Auto-generated method stub
      data.clear(); //原来的数据清除
      data.addAll(selectData()); 
      adapter.notifyDataSetChanged();
   }
   //查询工作  用于查询Data  raw_contact表 返回List数据 在刷新Adapter
   private List, String>> selectData() {
      //1.先查询 raw 获取_id 查出所有联系人.
      //2.循环查询--> 根据_id data表中(_id = raw_contacts_id)查询 data1数据
      Cursor cursor = contentResolver.query(Uri.parse(uri_raw), 
                   new String []{"_id","display_name"}, null, null, null);
      //cursor返回的cursor数量不定
      List, String>>  list =  new ArrayList,String>>();     
      while (cursor!= null && cursor.moveToNext()) {       
         String _id = cursor.getString(0);
         String dispalyName  = cursor.getString(1);
         Map, String> map = new HashMap, String>();
         map.put("_id", _id);
         map.put("display_Name", dispalyName);        
         //根据_id data查手机号
         Cursor cursor2 = contentResolver.query(Uri.parse(uri_phone), new String[]{"data1"}, 
               "raw_contact_id=?", new String []{_id}, null);
         //循环拿到手机号
         StringBuffer sb = new StringBuffer();
         while (cursor2!=null && cursor2.moveToNext()) {           
            sb.append(cursor2.getString(0)+"\n");           
         }
         cursor2.close(); //关闭游标
         map.put("data1", sb.toString());
         list.add(map);
      }    
      cursor.close();
      return list;
   }
   
   
   
}

你可能感兴趣的:(获取手机通讯录信息示例)