从Android手机获取电话号码

时间:2010-06-11 11:04:31

标签: java 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();

 }

}

似乎没有联系人有电话号码(我在模拟器上添加了2个联系人,我也尝试过我的HTC Desire)。问题是 if(Boolean.parseBoolean(hasPhone)) 总是返回false .. 我怎样才能获得正确的电话号码?

我试图在if语句之前调用drawContact(String name,String number)而不查询电话号码,并且它有效(它绘制了两次名称)。但是在LinearLayout上,它们不按字母顺序排序......我如何按字母顺序排序(类似于原始联系人应用程序)?

谢谢你的建议, 卢卡

1 个答案:

答案 0 :(得分:1)

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

相关问题