正在从联系人选取器获取号码



用户从联系人选取器中选取联系人后,我正在尝试获取联系人姓名和电话号码。我正在尝试使我的应用程序适用于SDK v3及更高版本,因此我创建了一个抽象类,该类只调用我需要的API。我已经有抽象类在工作(它选择了正确的API),我也有用于SDK v3,4的API在工作。我在使用ContactsContract的较新API工作时遇到问题。

我可以得到一个联系人的名字,但它检索的号码总是之前联系人ID的号码!示例:我有两个联系人"John Doe"one_answers"Jane Doe",在联系人中分别添加了编号"555-555-555"one_answers"777-77-777"。John Doe的ID=1,Jane Doe的ID=2。如果我想得到Jane Doe的电话号码,我会得到John的,555-555-5555。如果我想得到约翰的,我什么也得不到。检查if(cursor.moveToNext())是否失败。

你能帮我修一下吗?它把我逼疯了。我看了很多例子,总是得到同样的错误。

Intent数据是来自onActivityResult 的Intent数据


import java.util.ArrayList;

import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.provider.ContactsContract; import android.provider.ContactsContract.CommonDataKinds.Email; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.Contacts;

class NewContactsAdapterBridge extends ContactsAdapterBridge {

ArrayList<String> info = new ArrayList<String>(); ArrayList<String> getInfo (Activity a, Intent data) { Uri contactData = data.getData(); Cursor cursor = a.managedQuery(contactData, null, null, null, null); if (cursor.moveToFirst()) { String id = cursor.getString( cursor.getColumnIndex(ContactsContract.Contacts._ID)); String name = cursor.getString(cursor.getColumnIndexOrThrow (ContactsContract.Contacts.DISPLAY_NAME)); String hasPhoneNumber = cursor.getString(cursor.getColumnIndexOrThrow( ContactsContract.Contacts.HAS_PHONE_NUMBER)); info.add(name); if (Integer.parseInt(hasPhoneNumber) > 0) { Uri myPhoneUri = Uri.withAppendedPath( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, id); Cursor pCur = a.managedQuery( myPhoneUri, null, null, null, null); if (pCur.moveToNext()) { String number = pCur.getString( pCur.getColumnIndex (ContactsContract.CommonDataKinds.Phone.NUMBER)); info.add(number); } } } return info; } }
@Override  
protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
    if (resultCode == RESULT_OK) {  
        switch (requestCode) {  
        case CONTACT_PICKER_RESULT:
            final EditText phoneInput = (EditText) findViewById(R.id.phoneNumberInput);
            Cursor cursor = null;  
            String phoneNumber = "";
            List<String> allNumbers = new ArrayList<String>();
            int phoneIdx = 0;
            try {  
                Uri result = data.getData();  
                String id = result.getLastPathSegment();  
                cursor = getContentResolver().query(Phone.CONTENT_URI, null, Phone.CONTACT_ID + "=?", new String[] { id }, null);  
                phoneIdx = cursor.getColumnIndex(Phone.DATA);
                if (cursor.moveToFirst()) {
                    while (cursor.isAfterLast() == false) {
                        phoneNumber = cursor.getString(phoneIdx);
                        allNumbers.add(phoneNumber);
                        cursor.moveToNext();
                    }
                } else {
                    //no results actions
                }  
            } catch (Exception e) {  
               //error actions
            } finally {  
                if (cursor != null) {  
                    cursor.close();
                }
                final CharSequence[] items = allNumbers.toArray(new String[allNumbers.size()]);
                AlertDialog.Builder builder = new AlertDialog.Builder(your_class.this);
                builder.setTitle("Choose a number");
                builder.setItems(items, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int item) {
                        String selectedNumber = items[item].toString();
                        selectedNumber = selectedNumber.replace("-", "");
                        phoneInput.setText(selectedNumber);
                    }
                });
                AlertDialog alert = builder.create();
                if(allNumbers.size() > 1) {
                    alert.show();
                } else {
                    String selectedNumber = phoneNumber.toString();
                    selectedNumber = selectedNumber.replace("-", "");
                    phoneInput.setText(selectedNumber);
                }
                if (phoneNumber.length() == 0) {  
                    //no numbers found actions  
                }  
            }  
            break;  
        }  
    } else {
       //activity result error actions
    }  
}

您需要对此进行调整,以便与您的应用

配合使用

我能得到那个用例CONTACT_PICKER_RESULT。。。我上面用这个使用的代码

int PICK_CONTACT;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        b=(Button) findViewById(R.id.button1);
         et=(EditText) findViewById(R.id.editText1);
        b.setOnClickListener(this);
        //et.setOnClickListener(this);
            }
@Override
public void onClick(View v) {
    switch(v.getId())
    {
    case R.id.button1:
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
        startActivityForResult(intent, PICK_CONTACT);
        break;
   // case R.id.editText1:

      //  break;
    }
 Intent intent = new Intent(Intent.ACTION_PICK);
 intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
 startActivityForResult(intent, PICK_CONTACT); 

这些代码对您有帮助,我认为PICK活动只返回所选联系人的ID。从中,您可以查询联系人提供商,如果有多个电话号码,则提示用户选择其中一个。

U也可以使用

@Override  
protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
    if (resultCode == RESULT_OK) {  
    switch (requestCode) {  
    case CONTACT_PICKER_RESULT:
        final EditText phoneInput = (EditText) findViewById(R.id.phoneNumberInput);
        Cursor cursor = null;  
        String phoneNumber = "";
        List<String> allNumbers = new ArrayList<String>();
        int phoneIdx = 0;
        try {  
            Uri result = data.getData();  
            String id = result.getLastPathSegment();  
            cursor = getContentResolver().query(Phone.CONTENT_URI, null, Phone.CONTACT_ID + "=?", new String[] { id }, null);  
            phoneIdx = cursor.getColumnIndex(Phone.DATA);
            if (cursor.moveToFirst()) {
                while (cursor.isAfterLast() == false) {
                    phoneNumber = cursor.getString(phoneIdx);
                    allNumbers.add(phoneNumber);
                    cursor.moveToNext();
                }
            } else {
                //no results actions
            }  
        } catch (Exception e) {  
           //error actions
        } finally {  
            if (cursor != null) {  
                cursor.close();
            }
            final CharSequence[] items = allNumbers.toArray(new String[allNumbers.size()]);
            AlertDialog.Builder builder = new AlertDialog.Builder(your_class.this);
            builder.setTitle("Choose a number");
            builder.setItems(items, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int item) {
                    String selectedNumber = items[item].toString();
                    selectedNumber = selectedNumber.replace("-", "");
                    phoneInput.setText(selectedNumber);
                }
            });
            AlertDialog alert = builder.create();
            if(allNumbers.size() > 1) {
                alert.show();
            } else {
                String selectedNumber = phoneNumber.toString();
                selectedNumber = selectedNumber.replace("-", "");
                phoneInput.setText(selectedNumber);
            }
            if (phoneNumber.length() == 0) {  
                //no numbers found actions  
            }  
        }  
        break;  
    }  
} else {
   //activity result error actions
}  
}

对于初学者来说,请注意,不要忘记包含以下权限,否则它将无法使用

<uses-permission android:name="android.permission.READ_CONTACTS"/>

 switch (reqCode) {
        case (REQUEST_CODE_email):
            if (resultCode == Activity.RESULT_OK) {
                Uri contactData = data.getData();
                Cursor c = getContentResolver().query(contactData, null, null, null, null);
                if (c.moveToFirst()) {
                    String contactId = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));
                    String hasNumber = c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
                    String num = "";
                    if (Integer.valueOf(hasNumber) == 1) {
                        Cursor numbers = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
                        while (numbers.moveToNext()) {
                            num = numbers.getString(numbers.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
                            //Toast.makeText(getApplicationContext(), "Number=" + num, Toast.LENGTH_LONG).show();
                            //asdasdasdsa
                            if(getEmail(num).isEmpty()){
                                Toast.makeText(this, "Email Not Found In That Contact Try Another", Toast.LENGTH_SHORT).show();
                            }
                            else {
                                edt_email_contact.setText("" + getEmail(num));
                            }                            }
                    }
                }
                break;
            }
         case (REQUEST_CODE_number):
            if (resultCode == Activity.RESULT_OK) {
                Uri contactData = data.getData();
                Cursor c = getContentResolver().query(contactData, null, null, null, null);
                if (c.moveToFirst()) {
                    String contactId = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));
                    String hasNumber = c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
                    String num = "";
                    if (Integer.valueOf(hasNumber) == 1) {
                        Cursor numbers = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
                        while (numbers.moveToNext()) {
                            num = numbers.getString(numbers.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                            //Toast.makeText(getApplicationContext(), "Number=" + num, Toast.LENGTH_LONG).show();
                            //asdasdasdsa
                            edt_email_contact.setText("" + num);
                        }
                    }
                }
                break;
            }
    }

相关内容

  • 没有找到相关文章

最新更新