从android手机获取电话号码

问题描述:

首先,我很抱歉我的英语...从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上,它们不是按字母顺序排列的...我如何按字母顺序排序(类似于原始联系人应用程序)?

谢谢你的建议, 卢卡

检查documentation的parseBoolean()。 您可能想尝试将结果解析为int而不是布尔值。