0
首先,我很抱歉我的英語...從android手機獲取電話號碼
我有一個問題,從聯繫人獲取電話號碼。
這是我的代碼
import android.app.ListActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
public class TestContacts extends ListActivity {
private ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
private SimpleAdapter numbers;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contacts);
numbers = new SimpleAdapter(
this,
list,
R.layout.main_item_two_line_row,
new String[] { "line1","line2" },
new int[] { R.id.text1, R.id.text2 } );
setListAdapter(numbers);
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));
//check if the contact has a phone number
if (Boolean.parseBoolean(hasPhone)) {
Cursor phones = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId,
null, null);
while (phones.moveToNext()) {
// Get the phone number!?
String contactName = phones.getString(
phones.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(
phones.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
Toast.makeText(this, phoneNumber, Toast.LENGTH_LONG).show();
drawContact(contactName, phoneNumber);
}
phones.close();
}
}cursor.close();
}
private void drawContact(String name, String number){
HashMap<String,String> item = new HashMap<String,String>();
item.put("line1",name);
item.put("line2",number);
list.add(item);
numbers.notifyDataSetChanged();
}
}
It'seems沒有接觸有一個電話號碼(我已經添加在模擬器上2個觸點,我也試過在我的HTC Desire)。問題是, 如果(布爾.parseBoolean(hasPhone)) 返回始終爲false .. 我怎樣才能得到正確的電話號碼?
我試圖在if語句之前調用drawContact(String name,String number)而不查詢電話號碼,並且它工作(它繪製了兩次名稱)。但在LinearLayout上,它們不是按字母順序排列的...我如何按字母順序排序(類似於原始聯繫人應用程序)?
謝謝你的建議, 盧卡