2012-01-12 135 views
1

我想讓所有有電話號碼的聯繫人,並記錄他們的全名和電話號碼(以及將來他們的聯繫照片),但我被卡住了。這裏是我的代碼:如何獲取所有聯繫人全名和電話號碼,僅當他們有電話號碼?

String contacts = ""; 

    Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null); 
    while (cursor.moveToNext()) { 
     String contactId = cursor.getString(cursor.getColumnIndex( 
     ContactsContract.Contacts._ID)); 
     String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)); 
     if (hasPhone == "1") { 
      contacts += cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)) + ":" + "how to get number?" + "|"; 
     } 
    } 
    cursor.close(); 

字符串hasPhone應該包含「1」,如果聯繫人有一個電話號碼,然後添加名相關人員的電話號碼,以「接觸」的字符串。即使hasPhone包含「1」(從logcat中檢查),條件語句中的任何代碼都不會運行。另外,您如何獲得電話號碼,ContactsContract.Contacts中沒有任何內容。

+0

看到它一次可它是你 檢查http://stackoverflow.com/questions/12026173/android-cant-get-phone-number-有用一些聯繫人/ 12747910#12747910 – Jeetu 2012-10-05 14:07:17

回答

1

試試這個:

if (Integer.parseInt(hasPhone) > 0) { 
    Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +"="+ contactId, null, null); 
    phones.moveToNext(); //if you are interested in all contact phones do a while() 
    String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); 
    phones.close(); 
    contacts += cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)) + ":" + phoneNumber + "|"; 
} 
+0

使用此代碼後:http://pastebin.com/hrtFayqx我仍然沒有在Logcat中,沒有錯誤,沒有什麼,可悲的。我不明白爲什麼。我也有READ_CONTACTS權限。我也確信這個代碼正在被處理。 – Qasim 2012-01-13 00:21:16

+0

@Qasim:試試最後一個,適合我! – 2012-01-13 00:49:32

1

更改爲:爲對象平等

hasPhone.equals("1") 

==操作符檢查,也就是說,如果hasPhone是相同的對象爲「1」,這顯然是錯誤的。

你想檢查Lexicographic是否相等,所以你應該使用String的equals方法,它比較兩個對象字符串的等式,意思是檢查兩個字符的順序是否相同。

此外,考慮使用LookupKey,如下所述:http://developer.android.com/resources/articles/contacts.html

如果你想保存特定聯繫人將來參考。

+0

即使那樣,我仍然沒有得到任何東西。它真的很奇怪。 – Qasim 2012-01-13 00:22:39

相關問題