I am trying to fetch contact numbers in my application but it is showing only id and display name. Can anyone correct it? I don't know how to fetch the contact numbers. I am only trying to fetch the contact numbers not to add the contact numbers.
package com.data;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public final class ContactManager extends Activity
{
public static final String TAG = "ContactManager";
private Button mAddAccountButton;
private ListView mContactList;
private boolean mShowInvisible;
private CheckBox mShowInvisibleControl;
/**
* Called when the activity is first created. Responsible for initializing the UI.
*/
#Override
public void onCreate(Bundle savedInstanceState)
{
Log.v(TAG, "Activity State: onCreate()");
super.onCreate(savedInstanceState);
setContentView(R.layout.contact_manager);
// Obtain handles to UI objects
// mAddAccountButton = (Button) findViewById(R.id.addContactButton);
mContactList = (ListView) findViewById(R.id.contactList);
mShowInvisibleControl = (CheckBox) findViewById(R.id.showInvisible);
// Initialize class properties
mShowInvisible = false;
mShowInvisibleControl.setChecked(mShowInvisible);
// Register handler for UI elements
mShowInvisibleControl.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.d(TAG, "mShowInvisibleControl changed: " + isChecked);
mShowInvisible = isChecked;
populateContactList();
}
});
// Populate the contact list
populateContactList();
}
private void populateContactList() {
Cursor cursor = getContacts();
String[] pno=new String[cursor.getCount()];
if(cursor.getCount()>0)
{
int i=0;
if(cursor.moveToFirst())
{
do
{
pno[i++]=(String)cursor.getString(0).toString() +" "+ (String)cursor.getString(1);
}while(cursor.moveToNext());
}
}
ArrayAdapter<String> adapter=new ArrayAdapter<String>(ContactManager.this,android.R.layout.simple_list_item_1,pno);
mContactList.setAdapter(adapter);
}
private Cursor getContacts()
{
// Run query
Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
};
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '" +
(mShowInvisible ? "0" : "1") + "'";
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
return managedQuery(uri, projection, selection, selectionArgs, sortOrder);
}
}
Modify your query projection to include also the ContactsContract.Contacts.HAS_PHONE_NUMBER column.
Then, inside the do-while loop, you can do:
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (Integer.parseInt(hasPhone) > 0) {
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + contactId, null, null);
String phoneNumber;
while (cursor.moveToNext()) { //iterate over all contact phone numbers
phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
phones.close();
}
You need to use another content provider uri. I will point you to one answer of mine, so that I don't repeat myself in stackoverflow: https://stackoverflow.com/a/8646827/1108032. In this answer I fetch the name out of the phone number, but I really believe you can revert it easily.
You should use the Phone Uri or the new PhoneLookUp Uri to get display name and all phone numbers with contact id.
http://developer.android.com/reference/android/provider/ContactsContract.PhoneLookup.html
Related
I am posting my code here.
Please help me to get the email address of the contact.
Also I am getting a random list; please help me to sort the data as well.
package com.example.webwerks.retrievingcontactsdemo;
import android.app.Activity;
import android.app.ListActivity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.provider.ContactsContract;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import java.util.ArrayList;
public class MyActivity extends Activity {
private String name;
private String Number;
private String alternateNumber;
private String email_id;
RelativeLayout relativeLayout;
ListView listView;
ArrayList <String> arrayList = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
listView = (ListView)findViewById(android.R.id.list);
getInformation(this.getContentResolver());
// relativeLayout = (RelativeLayout)findViewById(R.id.layoutRelative);
}
public void getInformation(ContentResolver contentResolver){
Cursor phones = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,null,null,null);
while (phones.moveToNext()){
name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
Number = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
email_id = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
arrayList.add(name);
arrayList.add(Number);
arrayList.add(email_id);
}
phones.close();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,arrayList);
listView.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
This is my code. It gives me the contact name and contact number(primary) and email id column. Also, it shows me the contact number only.
And the data is not sorted according to my phone contact list.
Please help.
Thanks in advance :)
You need to execute another query using the id to get Email details of tat contact. SO check this code
Better to go with DataModel class:
public class ContactData
{
public String name;
public String email;
}
ArrayList<ContactData> data = new ArrayList<>();
public void getInformation(ContentResolver contentResolver){
Cursor phones = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,null,null,null);
while (phones.moveToNext()){
String id = phones.getString(phones.getColumnIndex(ContactsContract.Contacts._ID));
Cursor cur1 = contentResolver.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{id}, null);
while (cur1.moveToNext()) {
//to get the contact names
String name=cur1.getString(cur1.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
Log.e("Name :", name);
String email = cur1.getString(cur1.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
Log.e("Email", email);
if(email!=null){
Toast.makeText(this,
"Name : "+ name+" EMail : "+email, 1000)
.show();
}
}
dataList.add(contactData);
cur1.close();
}
phones.close();
}
cursor = context.getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
cursor.moveToFirst();
for (int i = 0; i < cursor.getCount(); i++) {
contact = getContact(cursor, context.getContentResolver());
cursor.moveToNext();
}
private Contact getContact(Cursor cur , ContentResolver cr){
String contactID = cur.getString(cur
.getColumnIndex(ContactsContract.Contacts._ID));
if (contactID != null)
{
// for reading all contact
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{contactID}, null);
while (pCur.moveToNext()) {
String contactNumber = pCur
.getString(pCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String contact_Number_Type = pCur
.getString(pCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
contact.setContact_Number(contactNumber);
contact.setContact_Number_Type(contact_Number_Type);
}
pCur.close();
// for reading all email id
Cursor emailCur = cr.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{contactID}, null);
while (emailCur.moveToNext()) {
String emailContact = emailCur
.getString(emailCur
.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
String emailType = emailCur
.getString(emailCur
.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
contact.setContact_Email(emailContact);
contact.setContact_Email_Type(emailType);
}
emailCur.close();
}
}
Here Contact is a bean class
I need to get contact name and relevant address from contact list in android. I get the contact name and their phone number, but unfortunately unable to get the address details. When I select the contact address, it will return null every time.
I searched the google as well as stackoverflow. But unable to find a solution. When I searched I found that, address details are in another separate table, but I searched that table with id, but didn't return the data from the address table. So please help me to solve this problem. Thanks in advance,
Please find the code snippet which I used to get the contact details,
package com.contact.contacts;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.StructuredPostal;
import android.app.Activity;
import android.database.Cursor;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
public class MainActivity extends Activity implements OnItemClickListener{
private ListView listView;
private List<ContactBean> list = new ArrayList<ContactBean>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listView = (ListView) findViewById(R.id.list);
listView.setOnItemClickListener(this);
Cursor cur_phone = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
null, null);
while (cur_phone.moveToNext()) {
String name = cur_phone
.getString(cur_phone
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = cur_phone
.getString(cur_phone
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String id = cur_phone.getString(cur_phone
.getColumnIndex(ContactsContract.Contacts._ID));
System.out.println("Cursor size : contact Name : "+name);
System.out.println("Cursor size : contact number : "+phoneNumber);
System.out.println("Cursor size : id : "+id);
Cursor cursor_address = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
cursor_address.close();
// get the data package containg the postal information for the contact
cursor_address = getContentResolver().query(ContactsContract.Data.CONTENT_URI,
new String[]{ StructuredPostal.STREET,
StructuredPostal.CITY,
StructuredPostal.POSTCODE},
ContactsContract.Data.CONTACT_ID + "=? AND " +
StructuredPostal.MIMETYPE + "=?",
new String[]{String.valueOf(id), StructuredPostal.CONTENT_ITEM_TYPE},
null);
cursor_address.moveToFirst();
System.out.println("Cursor size : Outside while");
while (cursor_address.moveToNext()) {
System.out.println("Cursor size : Inside while");
// This while statement is not running
if(cursor_address != null && cursor_address.moveToFirst())
{
if (cursor_address.getCount() > 0) {
String Street = cursor_address.getString(cursor_address.getColumnIndex(StructuredPostal.STREET));
System.out.println("Address : "+Street);
String Postcode = cursor_address.getString(cursor_address.getColumnIndex(StructuredPostal.POSTCODE));
String City = cursor_address.getString(cursor_address.getColumnIndex(StructuredPostal.CITY));
}
else
{
System.out.println("Cursor is : " + cursor_address);
Log.i("Contact : ", "Cursor :" + cursor_address);
}
}
else
{
System.out.println("Cursor Null : " + cursor_address);
Log.i("Contact App : ", "Cursor null" + cursor_address);
}
}
}
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
}
}
public ArrayList<String> getName(){
ArrayList<String> mdetail=new ArrayList<String>();
SQLiteDatabase db = this.getWritableDatabase();
String selectQuery = "SELECT "+COLUMN_PERSON_NAME+" from "+TABLE_DETAIL;
Cursor mCursor = db.rawQuery(selectQuery, null);
if(mCursor.moveToFirst()){
do {
mdetail.add(mCursor.getString(mCursor.getColumnIndex(COLUMN_PERSON_NAME)));
} while (mCursor.moveToNext());
}
mCursor.close();
db.close();
return mdetail;
}
if Your data is Sucessfully added in your database just use this code to retreive from database and show in list view like this....
if (!db.exists()) {
} else {
mListName=baseManager.getName();
listview.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,mListName));
}
Finally I solve the problem, Please find the below answer,
package com.contact.contacts;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.StructuredPostal;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnItemClickListener {
private ListView listView;
private List<ContactBean> list = new ArrayList<ContactBean>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listView = (ListView) findViewById(R.id.list);
listView.setOnItemClickListener(this);
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(
cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(
cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String phone = null;
String poBox = null;
String street = null;
String city = null;
String state = null;
String postalCode = null;
String country = null;
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
//Query for phone
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
// Get the phone number
phone = pCur.getString(
pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
pCur.close();
}
String addrWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] addrWhereParams = new String[]{id,
ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE};
Cursor addrCur = cr.query(ContactsContract.Data.CONTENT_URI,
null, addrWhere, addrWhereParams, null);
while(addrCur.moveToNext()) {
poBox = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POBOX));
street = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
city = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
state = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
postalCode = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));
country = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));
String type = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE));
}
addrCur.close();
ContactBean objContact = new ContactBean();
objContact.setName(name);
objContact.setPhoneNo(phone);
objContact.setAddressLine1(poBox);
objContact.setAddressLine2(street);
objContact.setCity(city);
objContact.setPostalCode(postalCode);
objContact.setCountry(country);
list.add(objContact);
ContactAdapter objAdapter = new ContactAdapter(ContactActivity.this,
R.layout.single_contact, list);
listView.setAdapter(objAdapter);
if (null != list && list.size() != 0) {
Collections.sort(list, new Comparator<ContactBean>() {
#Override
public int compare(ContactBean lhs, ContactBean rhs) {
return lhs.getName().compareTo(rhs.getName());
}
});
} else {
showToast("No Contact Found!!!");
}
}
}
}
private void showToast(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
#Override
public void onItemClick(AdapterView<?> listview, View v, int position,
long id) {
// Event for item click
}
}
I have a contact picker list with chckboxes of the contacts that have a phone number.
Now, my problem is that can't seem to get the checked contact's name and phone number.
Here is my code:
import android.app.ListActivity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class Create_Group extends ListActivity implements OnClickListener{
// List variables
public String[] Contacts = {};
public int[] to = {};
public ListView myListView;
Button save_button;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_group);
// Initializing the buttons according to their ID
save_button = (Button)findViewById(R.id.save_group_button);
// Defines listeners for the buttons
save_button.setOnClickListener(this);
Cursor mCursor = getContacts();
startManagingCursor(mCursor);
ListAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_multiple_choice, mCursor,
Contacts = new String[] {ContactsContract.Contacts.DISPLAY_NAME },
to = new int[] { android.R.id.text1 });
setListAdapter(adapter);
myListView = getListView();
myListView.setItemsCanFocus(false);
myListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}
private Cursor getContacts() {
// Run query
Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = new String[] { ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME};
String selection = ContactsContract.Contacts.HAS_PHONE_NUMBER + " = '"
+ ("1") + "'";
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME
+ " COLLATE LOCALIZED ASC";
return managedQuery(uri, projection, selection, selectionArgs,
sortOrder);
}
public void onClick(View src) {
Intent i;
switch (src.getId())
{
case R.id.save_group_button:
int checked_Names_Counter = 0;
// Goes over the list of contacts and checks which were checked
for (int j = 0; j < myListView.getCount(); j++)
{
if (myListView.isItemChecked(j) == true)
{
Cursor cur = getContacts();
ContentResolver contect_resolver = getContentResolver();
cur.moveToFirst();
/**
* Here I tried to compare the IDs but each list has different IDs so it didn't really help me...
// Converts the current checked name ID into a String
String Checked_ID = String.valueOf(myListView.getCheckedItemIds()[checked_Names_Counter]);
// Checks if the current checked ID matches the cursors ID, if not move the cursor to the next name
while (Checked_ID != cur.getString(cur.getColumnIndexOrThrow(ContactsContract.Contacts._ID)))
{
cur.moveToNext();
}
*/
/**
* Here I tried to compare the names, even though it's not a good pratice, and it didn't work either...
String Checked_Name = myListView.getAdapter().getItem(checked_Names_Counter).toString();
// Checks if the current checked ID matches the cursors ID, if not move the cursor to the next name
while (Checked_Name != cur.getString(cur.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME)))
{
cur.moveToNext();
}
*/
String id = cur.getString(cur.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
String name = "";
String no = "";
Cursor phoneCur = contect_resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { id }, null);
name = phoneCur.getString(phoneCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
no = phoneCur.getString(phoneCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
id = null;
name = null;
no = null;
phoneCur = null;
checked_Names_Counter++;
}
}
// Goes back to the Manage Groups screen
i = new Intent(this, Manage_Groups.class);
startActivity(i);
break;
}
}
}
Any ideas?
Thanks!!
It looks like you are so close, I used ListView.getCheckedItemIds() to return unique ids of the selected contacts:
public void onClick(View view) {
long[] ids = myListView.getCheckedItemIds();
for(long id : ids) {
Cursor contact = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { id + "" }, null);
// Do whatever you want with the data
}
}
Addition
I have a quick question about this code:
// Goes back to the Manage Groups screen
i = new Intent(this, Manage_Groups.class);
startActivity(i);
Does this bring the user back to a previous Activity? If so you should use finish(); instead. finish() ends the current Activity, taking it off the stack and freeing up any memory (less memory wasted means a faster app.) It also allows the previous Activity to restore the saved state when it left (filled in EditTexts, previous Spinner selections, toggle button and checkmarks, etc.) The Activity resumes where the user left off.
I am using the Android Eclair 2.1 platform.
The working behind this code is, it will access all the contacts from the Emulator and will display in the list view for each contact like this
Contact Name, Contact Number, Email
There are 2 issues for this code is
I did run the program, after that I created a new contact it won't be in alphabetical order
[ eg : when I create a name starting from B it wouldn't go after A, instead it go to the last place ]
2.If a contact has no Email or Number it will receive the previous contact's Email or Number
Here is the code
public class GetAllDatas extends Activity {
ListView lvItem;
private Button btnAdd;
String displayName="", emailAddress="", phoneNumber="";
ArrayList<String> contactlist=new ArrayList<String>();
ArrayAdapter<String> itemAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lvItem = (ListView)this.findViewById(R.id.lvitems);
btnAdd = (Button)this.findViewById(R.id.btnAddItem);
itemAdapter = new ArrayAdapter<String> (this,android.R.layout.simple_list_item_1,contactlist);
lvItem.setAdapter(itemAdapter);
btnAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
readContacts();
}
});
}
private void readContacts()
{
ContentResolver cr =getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
while (cursor.moveToNext())
{
displayName =Cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME) );
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
Cursor emails = cr.query(Email.CONTENT_URI,null,Email.CONTACT_ID + " = " + id, null, null);
while (emails.moveToNext())
{
emailAddress = emails.getString(emails.getColumnIndex(Email.DATA));
break;
}
emails.close();
if(Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PH ONE_NUMBER))) > 0)
{
Cursor pCur =cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.CommonDat aKinds.Phone.CONTACT_ID +" = ?",new String[]{id}, null);
while (pCur.moveToNext())
{
phoneNumber =pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
break;
}
pCur.close();
}
// To display the Details
contactlist.add(displayName+", "+phoneNumber+", "+ emailAddress+"\n");
itemAdapter.notifyDataSetChanged();
}
cursor.close();
}
}
Any link or site to refer and study to solve this problems if so send me the link ?
Check the tested code below
package stack.examples;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
public class GetAllDatas extends Activity {
ListView lvItem;
private Button btnAdd;
String displayName="", emailAddress="", phoneNumber="";
ArrayList<String> contactlist=new ArrayList<String>();
ArrayAdapter<String> itemAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lvItem = (ListView)this.findViewById(R.id.listView_items);
btnAdd = (Button)this.findViewById(R.id.btnAddItem);
itemAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,contactlist);
lvItem.setAdapter(itemAdapter);
btnAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
readContacts();
}
});
}
private void readContacts()
{
ContentResolver cr =getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
while (cursor.moveToNext())
{
displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
Cursor emails = cr.query(Email.CONTENT_URI,null,Email.CONTACT_ID + " = " + id, null, null);
while (emails.moveToNext())
{
emailAddress = emails.getString(emails.getColumnIndex(Email.DATA));
break;
}
emails.close();
if(Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",new String[]{id}, null);
while (pCur.moveToNext())
{
phoneNumber = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
break;
}
pCur.close();
}
contactlist.add(displayName+","+phoneNumber+","+ emailAddress);
}
cursor.close();
sortList(contactlist);
itemAdapter.notifyDataSetChanged();
}
private static void sortList(List<String> aItems){
Collections.sort(aItems, String.CASE_INSENSITIVE_ORDER);
}
}
To sort the ArrayList in Alphabetical order, you can use
Collections.sort(aItems, String.CASE_INSENSITIVE_ORDER);
Happy Coding !!!
When you query the database you are missing the orderBy:
public Cursor query (String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)
replace the last null with the column to sort by:
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
The last parameter of the query method expects the sorting order.
Please check the documentation query (Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder).
sortOrder How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort order, which may be unordered.
I am developing an application in which it is required to find the nature of a contact group means whether it is google group , phone group or sim group. How to find it.Please suggest me how to do it.
Thanks in advance.
The code below prints the contact name and type. I have not optimized it and it will print multiple records but I think you will know what to do.
package com.example.android.contactmanager;
import android.app.Activity;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.RawContacts;
import android.util.Log;
public final class ContactManager extends Activity{
/**
* Called when the activity is first created. Responsible for initializing the UI.
*/
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
printContactList();
}
/**
* Print contact data in logcat.
* SIM : Account_Type = com.anddroid.contacts.sim
* Phone : Depends on the manufacturer e.g For HTC : Account_Type = com.htc.android.pcsc
* Google : Account_Type = com.google
*/
private void printContactList() {
Cursor cursor = getContacts();
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
Log.d("Display_Name", cursor.getString(cursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME)));
Log.d("Account_Type", cursor.getString(cursor.getColumnIndex(RawContacts.ACCOUNT_TYPE)));
cursor.moveToNext();
}
}
/**
* Obtains the contact list for the currently selected account.
*
* #return A cursor for for accessing the contact list.
*/
private Cursor getContacts()
{
// Run query
Uri uri = ContactsContract.Data.CONTENT_URI;
String[] projection = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
RawContacts.ACCOUNT_TYPE
};
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
return managedQuery(uri, projection, null, selectionArgs, sortOrder);
}
}
I have same problem which you have mentioned i solved it like this way
ArrayList<GroupNameDetails> stateList = new ArrayList<GroupNameDetails>();
final String[] GROUP_PROJECTION = new String[]
{
ContactsContract.Groups._ID, ContactsContract.Groups.TITLE, ContactsContract.Groups.ACCOUNT_TYPE//this line will do the trick
};
Cursor cursor = getContentResolver().query(ContactsContract.Groups.CONTENT_URI, GROUP_PROJECTION, null,
null, ContactsContract.Groups.TITLE);
while (cursor.moveToNext()) {
String accountname=cursor.getString(cursor.getColumnIndex(ContactsContract.Groups.ACCOUNT_TYPE));
Toast.makeText(getBaseContext(), accountname, Toast.LENGTH_LONG).show();// and it will display group type
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Groups._ID));
Log.v("Test", id);
//ContactsContract.Groups.ACCOUNT_NAME
String gTitle = (cursor.getString(cursor.getColumnIndex(ContactsContract.Groups.TITLE)));
if(favGroupName.contains(gTitle)==false)
{
favGroupId.add(id);
favGroupName.add(gTitle);
GroupNameDetails _states = new GroupNameDetails(Long.parseLong(id),gTitle, false);
stateList.add(_states);
}
Log.v("Test", gTitle);
if (gTitle.contains("Favorite_")) {
gTitle = "Favorites";
}
}