2012-05-15 41 views
6

Tôi có một mã snappet để truy cập Danh bạ. Khi người dùng nhấp vào nút thì danh sách liên hệ sẽ được mở và người dùng có thể chọn một người từ danh sách liên hệ và địa chỉ email của người đó phải được viết trên văn bản. Tôi có thể nhận email từ những người mà người dùng chọn. Nhưng tôi không thể đặt nó vào văn bản.Truy cập danh bạ và nhận địa chỉ email

static String email = ""; 


imgbtnaddfromcontacts.setOnClickListener(new OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       if (v == imgbtnaddfromcontacts) { 
        try 
        { 
         Intent intent = new Intent(Intent.ACTION_PICK, 
           ContactsContract.Contacts.CONTENT_URI); 
         startActivityForResult(intent, 1); 

        } catch (Exception e) { 
         e.printStackTrace(); 
         Log.e("Error in intent : ", e.toString()); 
        } 
       } 
      } 
     }); 
     kimeTxt.setText(email); 
    } 

    @Override 
    public void onActivityResult(int reqCode, int resultCode, Intent data) { 
     super.onActivityResult(reqCode, resultCode, data); 

     try { 
      if (resultCode == Activity.RESULT_OK) { 
       // Get data 
       Uri contactData = data.getData(); 
       // Cursor 
       Cursor cur = managedQuery(contactData, null, null, null, null); 
       ContentResolver contect_resolver = getContentResolver(); 

       // List 
       if (cur.moveToFirst()) { 
        String id = cur 
          .getString(cur 
            .getColumnIndexOrThrow(ContactsContract.Contacts._ID)); 

        Cursor phoneCur = contect_resolver.query(
          ContactsContract.CommonDataKinds.Phone.CONTENT_URI, 
          null, 
          ContactsContract.CommonDataKinds.Phone.CONTACT_ID 
            + " = ?", new String[] { id }, null); 

        Cursor emailCur = contect_resolver.query(
          ContactsContract.CommonDataKinds.Email.CONTENT_URI, 
          null, 
          ContactsContract.CommonDataKinds.Email.CONTACT_ID 
            + " = ?", new String[] { id }, null); 

        if (phoneCur.moveToFirst()) { 
         name = phoneCur 
           .getString(phoneCur 
             .getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)); 
         no = phoneCur 
           .getString(phoneCur 
             .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); 

        } 

        while (emailCur.moveToNext()) { 
         // This would allow you get several email addresses 
         // if the email addresses were stored in an array 
         email = emailCur 
           .getString(emailCur 
             .getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA)); 

         if (email != null) 
         { 
          seciliEmail = email; 
         } else { 
          Toast.makeText(EpostaIletActivity.this, 
            "Kişinin eposta hesabı bulunmamaktadır.", 
            Toast.LENGTH_SHORT); 
          Log.w("Error: ", "Kişinin eposta hesabı yok."); 
         } 
        } 

        Log.e("Phone no & name & email :***: ", name + " : " + no + ":" + email); 
        // txt.append(name + " : " + no + "\n"); 

        id = null; 
        name = null; 
        no = null; 
        seciliEmail = "xxx"; 
        phoneCur = null; 
        emailCur.close(); 
       } 
       contect_resolver = null; 
       cur = null; 
       // populateContacts(); 

      } 
     } catch (IllegalArgumentException e) { 
      e.printStackTrace(); 
      Log.e("IllegalArgumentException :: ", e.toString()); 
     } catch (Exception e) { 
      e.printStackTrace(); 
      Log.e("Error :: ", e.toString()); 
     } 
    } 

Trả lời

21

Am sử dụng mã dưới đây để nhận địa chỉ email từ liên lạc đã chọn -

public void doLaunchContactPicker(View view) { 
    Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,Contacts.CONTENT_URI); 
    startActivityForResult(contactPickerIntent, CONTACT_PICKER_RESULT); 
} 

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) 
{ 
    if (resultCode == RESULT_OK) { 
     switch (requestCode) 
     { 
     case CONTACT_PICKER_RESULT: 
      Cursor cursor = null; 
      String email = "", name = ""; 
      try { 
       Uri result = data.getData(); 
       Log.v(DEBUG_TAG, "Got a contact result: " + result.toString()); 

       // get the contact id from the Uri 
       String id = result.getLastPathSegment(); 

       // query for everything email 
       cursor = getContentResolver().query(Email.CONTENT_URI, null, Email.CONTACT_ID + "=?", new String[] { id }, null); 

       int nameId = cursor.getColumnIndex(Contacts.DISPLAY_NAME); 

       int emailIdx = cursor.getColumnIndex(Email.DATA); 

       // let's just get the first email 
       if (cursor.moveToFirst()) { 
        email = cursor.getString(emailIdx); 
        name = cursor.getString(nameId); 
        Log.v(DEBUG_TAG, "Got email: " + email); 
       } else { 
        Log.w(DEBUG_TAG, "No results"); 
       } 
      } catch (Exception e) { 
       Log.e(DEBUG_TAG, "Failed to get email data", e); 
      } finally { 
       if (cursor != null) { 
        cursor.close(); 
       } 
       EditText emailEntry = (EditText) findViewById(R.id.editTextv); 
       EditText personEntry = (EditText) findViewById(R.id.person); 
       emailEntry.setText(email); 
       personEntry.setText(name); 
       if (email.length() == 0 && name.length() == 0) 
       { 
        Toast.makeText(this, "No Email for Selected Contact",Toast.LENGTH_LONG).show(); 
       } 
      } 
      break; 
     } 

    } else { 
     Log.w(DEBUG_TAG, "Warning: activity result not ok"); 
    } 
} 

doLaunchContactPicker là một onclick của Button Sử dụng mã bất cứ nơi nào bạn muốn.

+1

+1, Nice câu trả lời – Venky

+2

Tôi chắc chắn đây là một câu trả lời tuyệt vời tại một thời điểm. Danh bạ được depricated ở cấp API 8. ActivityNotFoundException trong API 17. – stephen

+0

xuất sắc ................ – kgandroid

0
You can achieve it like this  

    public class Abc extends Activity{ 
     EditText kimeTxt; 
      Intent i;         
       Bundle b ;  
      @Override 

      protected void onCreate(Bundle savedInstanceState) { 
       // TODO Auto-generated method stub 
       super.onCreate(savedInstanceState); 
       setContentView(R.layout.add_course); 
     kimeTxt= (EditText)findViewById(R.id.emailid); 

     } 


     @Override 
      public void onActivityResult(int reqCode, int resultCode, Intent data) { 
       super.onActivityResult(reqCode, resultCode, data); 

       try { 
        if (resultCode == Activity.RESULT_OK) { 
         // Get data 
         Uri contactData = data.getData(); 
         // Cursor 
         Cursor cur = managedQuery(contactData, null, null, null, null); 
         ContentResolver contect_resolver = getContentResolver(); 

         // List 
         if (cur.moveToFirst()) { 
          String id = cur 
            .getString(cur 
              .getColumnIndexOrThrow(ContactsContract.Contacts._ID)); 

          Cursor phoneCur = contect_resolver.query(
            ContactsContract.CommonDataKinds.Phone.CONTENT_URI, 
            null, 
            ContactsContract.CommonDataKinds.Phone.CONTACT_ID 
              + " = ?", new String[] { id }, null); 

          Cursor emailCur = contect_resolver.query(
            ContactsContract.CommonDataKinds.Email.CONTENT_URI, 
            null, 
            ContactsContract.CommonDataKinds.Email.CONTACT_ID 
              + " = ?", new String[] { id }, null); 

          if (phoneCur.moveToFirst()) { 
           name = phoneCur 
             .getString(phoneCur 
               .getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)); 
           no = phoneCur 
             .getString(phoneCur 
               .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); 

          } 

          while (emailCur.moveToNext()) { 
           // This would allow you get several email addresses 
           // if the email addresses were stored in an array 
           email = emailCur 
             .getString(emailCur 
               .getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA)); 

           if (email != null) 
           { 
            seciliEmail = email; 
           } else { 
            Toast.makeText(EpostaIletActivity.this, 
              "Kişinin eposta hesabı bulunmamaktadır.", 
              Toast.LENGTH_SHORT); 
            Log.w("Error: ", "Kişinin eposta hesabı yok."); 
           } 
          } 

          Log.e("Phone no & name & email :***: ", name + " : " + no + ":" + email); 
          // txt.append(name + " : " + no + "\n"); 

          id = null; 
          name = null; 
          no = null; 
          seciliEmail = "xxx"; 
          phoneCur = null; 
          emailCur.close(); 
         } 


    // can set email id here 



     kimeTxt.setText(email); 


         contect_resolver = null; 
         cur = null; 
         // populateContacts(); 

        } 
       } catch (IllegalArgumentException e) { 
        e.printStackTrace(); 
        Log.e("IllegalArgumentException :: ", e.toString()); 
       } catch (Exception e) { 
        e.printStackTrace(); 
        Log.e("Error :: ", e.toString()); 
       } 
     } 
3

chắc chắn rằng ứng dụng của bạn đã có sự cho phép, nếu không bạn sẽ nhận được ngoại lệ kỳ lạ

trong AndroidManifest.xml:

<uses-permission android:name="android.permission.READ_CONTACTS" /> 
Các vấn đề liên quan