从联系人选择器联系电话号码读取错误

时间:2013-06-12 08:15:44

标签: java android

我正在尝试联系人屏幕,当用户从那里选择联系人时,它的姓名和电话号码将显示在onActivityResult屏幕中的Toast消息中。问题是当我选择联系人时,当我试图显示数字错误时,它的名字显示在吐司中:

java.lang.illegalStateException:Couldn't read row 0,col -1 from CursorWindow.Make sure the Cursor is initialized correctly before accessing data from it.

这是我的onActivityResult

代码
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    if(resultCode==Activity.RESULT_OK){
        switch(requestCode){
        case 1:
            Cursor c=managedQuery(data.getData(), null, null, null, null);              
            if(c.moveToFirst()){
                try{
                String name=c.getString(c.getColumnIndex(People.NAME));
                String no=c.getString(c.getColumnIndex(People.NUMBER));
                Toast.makeText(getApplicationContext(), no, 1).show();
                }
                catch(Exception e){
                    Log.v("error", e.toString());
                }
            }
            break;
        }           
    }
}

1 个答案:

答案 0 :(得分:0)

请尝试以下提及的代码将帮助您...

`Uri contactdate = data.getData();
                Cursor cursor = managedQuery(contactdate, null, null, null,null);
                if(cursor.moveToFirst()){
                    String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                    String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
                    if(hasPhone.equalsIgnoreCase("1")){
                        Cursor phones = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                                null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + id, null,null);
                        phones.moveToFirst();
                        String phoneNumebr = phones.getString(phones.getColumnIndex("data1"));
                        String mFormatedPhoneNumber = phoneNumebr.replace("-", "").replace(" ", "").replace("(","").replace(")", "");
                        Log.i(TAG, "Phone Number :"+mFormatedPhoneNumber);                      

}else{ Log.i(TAG, "Phone Number Not available"); } Log.i(TAG, "Name :"+cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME))); }`