如何在android中只选择一个联系人

时间:2013-03-20 16:54:47

标签: android android-contacts contactscontract

我想在我的应用中只选择一个联系人。但问题是当我选择一个联系人时,它会选择我所有的联系人。请查看我的代码。

以下是代码:

btnContact.setOnClickListener(new View.OnClickListener() {                        
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
            startActivityForResult(intent, RQS_PICK_CONTACT);
        }
    });

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  // TODO Auto-generated method stub
  super.onActivityResult(requestCode, resultCode, data);
  ContentResolver cr = getContentResolver();
  Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);

  if (cur.getCount() > 0) {   
   while (cur.moveToNext()) {
       String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));

       if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
           // get the phone number
           Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null, 
                                  ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?", 
                                  new String[]{id}, null);
           while (pCur.moveToNext()) {
               String name = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                 String phone = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                 txtPhoneNo.append(name + " <" + phone + ">");
           }               
           pCur.close();
 // Get note.......
           String noteWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?"; 
           String[] noteWhereParams = new String[]{id, 
           ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE}; 
                   Cursor noteCur = cr.query(ContactsContract.Data.CONTENT_URI, null, noteWhere, noteWhereParams, null); 
           if (noteCur.moveToFirst()) { 
               String note = noteCur.getString(noteCur.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE));
               textCode.append(note);
               try {
                File myFile = new File("/sdcard/file.txt");
                myFile.createNewFile();
                FileOutputStream fOut = new FileOutputStream(myFile);
                OutputStreamWriter myOutWriter = 
                                        new OutputStreamWriter(fOut);
                myOutWriter.append(textCode.getText());
                myOutWriter.close();
                fOut.close();

            } catch (Exception e) {

            }
           } 
           noteCur.close();

       }}
  }
}

我的代码有问题吗?

提前致谢。

0 个答案:

没有答案