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.
Related
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 have a hashmap which i would like to display. The user will input a name into an editText and when they click the search button, it should go through the hashmap and show the entry that matches the text in edittext with the key.
HashMap<String, Staff> h = new HashMap<String, Staff>();
Staff staff = new Staff("Thomas", "133", "thomas133#email.com");
h.put("Thomsas", staff);
I have tried to adapt the notepad app
package android;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.project.R;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SimpleCursorAdapter;
public class SingleStaff extends ListActivity {
private DBAdapter mDbHelper;
private EditText staffName;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.searchstaff);
staffName = (EditText) findViewById(R.id.staffname);
mDbHelper = new DBAdapter(this);
mDbHelper.open();
registerForContextMenu(getListView());
Button search = (Button) findViewById(R.id.confirm);
search.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
String a = staffName.getText().toString();
fillData(a);
}
});
}
private void fillData(String staffName) {
Cursor notesCursor = mDbHelper.fetchSingleStaff(staffName);
startManagingCursor(notesCursor);
// Create an array to specify the fields we want to display in the list (only TITLE)
String[] from = new String[]{ DBAdapter.STAFF_NAME, DBAdapter.STAFF_ROOM, DBAdapter.STAFF_EMAIL};
// and an array of the fields we want to bind those fields to (in this case just text1)
int[] to = new int[]{R.id.text1, R.id.text2, R.id.text3};
// Now create a simple cursor adapter and set it to display
SimpleCursorAdapter notes =
new SimpleCursorAdapter(this, R.layout.note_row_staff, notesCursor, from, to);
setListAdapter(notes);
}
}
When i run the application and have typed in for example "Thomas" in the edittext and clicked search i get an error message,
android.database.sqlite.SQLiteException: no such column: Thomas: , while compiling: SELECT
DISTINCT _id, name, room, email FROM staff WHERE name=Thomas
You can change your query line to (notice the single quote around staffName:
Cursor mCursor = mDb.query(true, STAFF_TABLE, new String[] {STAFF_ROWID, STAFF_NAME, STAFF_ROOM, STAFF_EMAIL}, STAFF_NAME + "='" + staffName + "'", null, null, null, null, null);
It is better to use ? placeholders to avoid that kind of problem (untested)
public Cursor fetchSingleStaff(String staffName) throws SQLException {
String[] arg = new String[] { staffName };
Cursor mCursor = mDb.query(true, STAFF_TABLE, new String[] {STAFF_ROWID, STAFF_NAME, STAFF_ROOM, STAFF_EMAIL}, STAFF_NAME + "=?", arg , null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
If you want to use a map, you can overload the above method and set the staffName with the corresponding value in your map
public Cursor fetchSingleStaff(Map<String, Staff> m) throws SQLException {
return fetchSingleStaff(m.getFirstName); // m.getFirstName() should be mapped the `Thomas` in `Staff` - Update according to your implementation
}
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
I know what has to be done.. this is what i have to do..
create a custom listview (with checkboxes on the list row on the left) in your app, with the adapter getting data one be one to your app from contacts app using a service or thread, then inflate it on the view
But I am having trouble implementing it...
i knw the basics too..then pass that arraylist in the adapter...
If any body can help me out.. I am stuck for past week on this... I want to get it over with...
ArrayList<WhateverTypeYouWant> mArrayList = new ArrayList<WhateverTypeYouWant>();
for(mCursor.moveToFirst(); mCursor.moveToNext(); mCursor.isAfterLast()) {
// The Cursor is now set to the right position
mArrayList.add(mCursor.getWhateverTypeYouWant(WHATEVER_COLUMN_INDEX_YOU_WANT));
}
Here is the code...
package com.exiom.productcatalogue;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class WebexAttendeeList extends Activity {
ListView lstAttends;
ListView lstContacts;
private ArrayList<String> aAttendees = new ArrayList<String>();
private ArrayList<String> aContacts= new ArrayList<String>();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webexattendees);
// lstContacts = (ListView)findViewById(R.id.lstContacts);
lstAttends = (ListView)findViewById(R.id.lstAttendees);
Cursor cur = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
HashMap<String, String> sContact = new HashMap<String, String>();
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));
sContact = new HashMap<String, String>();
Cursor emailCur = getContentResolver().query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{id}, null);
while (emailCur.moveToNext()) {
// This would allow you get several email addresses
// if the email addresses were stored in an array
String email = emailCur.getString(
emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
// String emailType = emailCur.getString(
// emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
sContact.put("name", name);
sContact.put("email", email);
mylist.add(sContact);
aAttendees.add(name);
}
emailCur.close();
}
cur.close();
}
// SimpleAdapter mAttendees = new SimpleAdapter(this, mylist, R.layout.multicolumnlayout,
// new String[] {"name", "email"}, new int[] {R.id.NAME, R.id.EMAIL});
// lstContacts.setAdapter(mAttendees);
// lstContacts.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
ArrayAdapter<String> attendAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, aAttendees);
lstAttends.setAdapter(attendAdapter);
lstAttends.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
Button btnStart = (Button)this.findViewById(R.id.btnStartWebex);
btnStart.setOnClickListener(mStartButtonListener);
Button btnCancel = (Button)this.findViewById(R.id.btnWebexCancel);
btnCancel.setOnClickListener(mCancelButtonListener);
// lstContacts.setOnClickListener(mSelectAttendee);
}
public void StartWebEx()
{
// WebexClient webex = null ;
// String webExId = "";
// String backUrl = "";
//
// webex.getLoginUrl(webExId, backUrl);
int len = lstAttends.getCount();
SparseBooleanArray checked = lstAttends.getCheckedItemPositions();
for (int i = 0; i < len; i++)
if (checked.get(i)) {
String item = aAttendees.get(i).toString();
/* do whatever you want with the checked item */
}
}
private OnClickListener mStartButtonListener = new OnClickListener() {
public void onClick(View v) {
// do something when the button is clicked
Toast.makeText(getBaseContext(), "Starting WebEx...",Toast.LENGTH_SHORT).show();
// String sSQLCmd = "update U_WEBEX_SETTING set webex_url = '"+edtWURL.getText()+"', "
// + "webex_id = '"+edtWID.getText()+"', "
// + "webex_pw = '"+edtWPW.getText()+"'";
//
// db.execSQL(sSQLCmd);
StartWebEx();
finish();
};
};
private OnClickListener mCancelButtonListener = new OnClickListener() {
public void onClick(View v) {
// do something when the button is clicked
Toast.makeText(getBaseContext(), "Exiting WebEx...",Toast.LENGTH_LONG).show();
finish();
};
};
private OnClickListener mSelectAttendee = new OnClickListener() {
public void onClick(View v) {
// do something when the button is clicked
// aAttendees.add(lstContacts);
Toast.makeText(getBaseContext(), "Selected...",Toast.LENGTH_LONG).show();
finish();
};
};
}
I think, this will be helpful to you.
Content Providers
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";
}
}