get Phone numbers from android phone
Posted
by Luca
on Stack Overflow
See other posts from Stack Overflow
or by Luca
Published on 2010-06-11T11:04:31Z
Indexed on
2010/06/11
11:32 UTC
Read the original article
Hit count: 289
Hi! First of all i'm sorry for my english...
I've a problem getting phone numbers from contacts.
That's my code
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 that no contact have a phone number (i've added 2 contacts on the emulator and i've tried also on my HTC Desire). The problem is that if (Boolean.parseBoolean(hasPhone)) returns always false.. How can i get correctly phone numbers?
I've tried to call drawContact(String name, String number) before the if statement without querying for the phone number, and it worked (it draws two times the name). but on the LinearLayout they are not ordered alphabetically... how can i order alphabetically (similar to the original contacts app)?
thank you in advice, Luca
© Stack Overflow or respective owner