获取结构名称每次只返回第一次联系给定名称。安卓

时间:2011-08-04 09:51:21

标签: android

嗨frnds我想获取联系人列表中的所有给定名称,但每次当我调用此方法时,它会在每次返回联系人列表的第一个值时请在下面的代码中查看。如何在每次getName(long _id)方法调用时读取下一个值....

public String [] getName(long _id)
{
    String Given = null ;
    String family = null ;
    try {
        String whereName = ContactsContract.Data.MIMETYPE + " = ?";
        String[] whereNameParams = new String[] { ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE };
        Cursor cursor = getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, whereName, whereNameParams, ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME);

        if(cursor != null) {
            while (cursor.moveToNext()) {  
                // This would allow you get several email addresses  
                // if the email addresses were stored in an array  
                Given = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME));
                // family = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME));

                // TODO Auto-generated method stub
                if(Given != null)
                    break;
            }
        }       
    } catch (Exception e) {
        Log.i("test", "Exception " + e.toString());
    } finally {
        if(cursor != null) {
            cursor.deactivate();
            cursor.close();             
        }
    }
    //return emailid;
    //return emailType;

    Log.i("RETURN given name.....", Given);   
    return new String[] { Given};       
}

1 个答案:

答案 0 :(得分:0)

您发布的代码在任何情况下都不起作用。您无法在try{}块中声明变量并在finally{}块中使用它。但我们先谈谈你的问题。

查看你的代码,我发现你永远不会使用_id参数,因此总是得到相同的名称。您需要检查当前行的ID是否与getName(long _id)中作为参数获得的ID相同。这样的事情应该做:

while (cursor.moveToNext()) {

                if (cursor.getLong(cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.StructuredName._ID)) == _id) {
                    Given = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME));
                    break;
                }
            }

希望这有帮助!

请记住在cursor区块前至少提出try{}的声明:)