访问联系人列表android

时间:2014-05-26 14:20:07

标签: android

我已设法访问联系人列表以选择联系人并在editText中输入数字。我面临的唯一问题是,当我在联系人列表中按后退按钮时,应用程序停止。你能帮忙吗?

Intent contactIntent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
@Override
protected void onActivityResult(int reqCode, int resultCode, Intent intent) 
{
    super.onActivityResult(reqCode, resultCode, intent);
    switch (reqCode) {
    case ADDRESS_REQUEST2:
        EditText edittext2 = (EditText) findViewById(R.id.number2);
        Uri uri2 = intent.getData();
        Cursor cursor2 = getContentResolver().query(uri2, null, null, null, null);
        cursor2.moveToFirst();
        String phoneNumber2 = cursor2.getString(cursor2.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

        edittext2.setText(phoneNumber2);
        break;
    case ADDRESS_REQUEST3:
        EditText edittext3 = (EditText) findViewById(R.id.number3);
        Uri uri3 = intent.getData();
        Cursor cursor3 = getContentResolver().query(uri3, null, null, null, null);
        cursor3.moveToFirst();
        String phoneNumber3 = cursor3.getString(cursor3.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

        edittext3.setText(phoneNumber3);
        break;
    case ADDRESS_REQUEST4:
        EditText edittext4 = (EditText) findViewById(R.id.number4);
        Uri uri4 = intent.getData();
        Cursor cursor4 = getContentResolver().query(uri4, null, null, null, null);
        cursor4.moveToFirst();
        String phoneNumber4 = cursor4.getString(cursor4.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

        edittext4.setText(phoneNumber4);
        break;
    default:
        EditText edittext1 = (EditText) findViewById(R.id.number1);
        Uri uri1 = intent.getData();
        Cursor cursor1 = getContentResolver().query(uri1, null, null, null, null);
        cursor1.moveToFirst();
        String phoneNumber1 = cursor1.getString(cursor1.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
        edittext1.setText(phoneNumber1);
        break;
    }


}

1 个答案:

答案 0 :(得分:0)

您需要检查

if (resultCode == RESULT_OK) { ...

首先。

当您退出Contact Picker活动而不选择一个时,不会返回Intent,因此会返回NullPointerException。 resultCode值指示操作是否成功。作为一般规则,成功操作将为RESULT_OK,否则为RESULT_CANCELED

作为一个完全不相关的,你应该重构那个方法......