I have an app that lists the users contacts in a listview with a checkbox using a simple cursor adapter. Upon pressing a button i would like to save the checked items to an array with a name the user has chosen using edittext so that i can display it later. Also, i was wondering how to create an array or array names or something similar allowing me to select the arrays that have been created.
Specific code is much appreciated.
Thanks in advance for your help.
here is my code:
package com.contacts5;
import android.app.ListActivity;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class contacts5 extends ListActivity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Cursor mCursor = getContacts();
startManagingCursor(mCursor);
ListAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_multiple_choice,
mCursor,
new String[] { ContactsContract.Contacts.DISPLAY_NAME ,
ContactsContract.Contacts._ID},
new int[] { android.R.id.text1, android.R.id.text2 });
setListAdapter(adapter);
final ListView listView = getListView();
listView.setItemsCanFocus(false);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}
private Cursor getContacts()
{
Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = new String[] { ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME };
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '"
+ ("1") + "'";
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME+ " COLLATE LOCALIZED ASC";
return managedQuery(uri, projection, selection, selectionArgs,sortOrder);
}
}
Related
i am trying to write a program that would display the id, name and phone number of a contact in android. So far the Id and Names of the contact are displayed but the number of the contact doesn't. Can someone help me, below is the code for my program:
package com.example.oghenekaroedoh.provider;
import android.app.ListActivity;
import android.content.CursorLoader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.widget.CursorAdapter;
import android.widget.SimpleCursorAdapter;
public class Provider2Activity extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_provider);
Uri allContacts = ContactsContract.Contacts.CONTENT_URI;
//query string for our contacts
//Uri allContacts = Uri.parse("content://contacts/people");
//declare our cursor
Cursor c;
String[] projection = new String[]
{ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.HAS_PHONE_NUMBER};
//---detect the android version
//---Projection, Filtering, and sorting
/* >>The second parameter of the managedQuery() method (third parameter for the CursorLoader class)
controls how many columns are returned by the query; this parameter is known as the projection
>>The third parameter of the managedQuery() method (fourth parameter for the CursorLoader class)
enable you to specify a SQL WHERE clause to filter the result of the query
>>The fourth parameter of the managedQuery() method (the fifth parameter for the CursorLoader class)
enables you to specify a SQL ORDER BY clause to sort the result of the query, either in ascending or descending order
* */
if (android.os.Build.VERSION.SDK_INT <11) {
//---if the device ids running on OS before Honeycomb
//use the managedQuery() of the Activity class to retrieve a managed cursor
c = managedQuery(allContacts, projection, null, null, null);
}
else {
//---Honeycomb and later use the cursor loader class to retrieve managed cursor---
CursorLoader cursorLoader = new CursorLoader(
this,
allContacts,
projection,
null,
null ,
null);
c = cursorLoader.loadInBackground();
}
//create columns for the contacts display name and the column
String[] columns = new String[] {
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts._ID};
int[] views = new int[] {R.id.contactName, R.id.contactID};
SimpleCursorAdapter adapter;
//detect the android version again..s
if (android.os.Build.VERSION.SDK_INT <11) {
//---if it is before Honeycomb---
//use the SimpleCursorAdapter class to map the cursor to a view (like textViews imageViews e.t.c)
adapter = new SimpleCursorAdapter(
this, R.layout.activity_provider, c, columns, views);
}
else {
//---Honeycomb and later---
////use the SimpleCursorAdapter class to map the cursor to a view (like textViews imageViews e.t.c)
//with an extra parameter known as CursorAdapter.FLAG_REGISTER_CURRENT_OBSERVER
adapter = new SimpleCursorAdapter(
this, R.layout.activity_provider, c, columns, views,
CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
}
this.setListAdapter(adapter);
PrintContacts(c);
}
private void PrintContacts(Cursor c)
{
//---display the contact id and name and phone number----
if (c.moveToFirst()) {
do{
//---get the contact id and name
String contactID = c.getString(c.getColumnIndex(
ContactsContract.Contacts._ID));
String contactDisplayName =
c.getString(c.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME));
Log.v("Content Providers", contactID + ", " +
contactDisplayName);
//---get phone number---
int hasPhone =
c.getInt(c.getColumnIndex(
ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (hasPhone == 1) {
Cursor phoneCursor =
getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " +
contactID, null, null);
while (phoneCursor.moveToNext()) {
Log.v("Content Providers",
phoneCursor.getString(
phoneCursor.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER)));
}
phoneCursor.close();
}
} while (c.moveToNext());
}
}
}
I got your example working by adding a CustomAdapter MyClassAdapter which extends ArrayAdapter, and populating an ArrayList of Contact objects.
import android.app.ListActivity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.CursorLoader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class Provider2Activity extends ListActivity {
ArrayList<Contact> contacts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_provider2);
contacts = new ArrayList<Contact>();
Uri allContacts = ContactsContract.Contacts.CONTENT_URI;
//declare our cursor
Cursor c;
String[] projection = new String[]
{ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.HAS_PHONE_NUMBER};
/* >>The second parameter of the managedQuery() method (third parameter for the CursorLoader class)
controls how many columns are returned by the query; this parameter is known as the projection
>>The third parameter of the managedQuery() method (fourth parameter for the CursorLoader class)
enable you to specify a SQL WHERE clause to filter the result of the query
>>The fourth parameter of the managedQuery() method (the fifth parameter for the CursorLoader class)
enables you to specify a SQL ORDER BY clause to sort the result of the query, either in ascending or descending order
* */
if (android.os.Build.VERSION.SDK_INT <11) {
//---if the device ids running on OS before Honeycomb
//use the managedQuery() of the Activity class to retrieve a managed cursor
c = managedQuery(allContacts, projection, null, null, null);
}
else {
//---Honeycomb and later use the cursor loader class to retrieve managed cursor---
CursorLoader cursorLoader = new CursorLoader(
this,
allContacts,
projection,
null,
null ,
null);
c = cursorLoader.loadInBackground();
}
PrintContacts(c);
MyClassAdapter adapter;
//detect the android version again..
if (android.os.Build.VERSION.SDK_INT <11) {
//---if it is before Honeycomb---
adapter = new MyClassAdapter(
this, R.layout.row_line, contacts);
}
else {
//---Honeycomb and later---
adapter = new MyClassAdapter(
this, R.layout.row_line, contacts);
}
this.setListAdapter(adapter);
}
private void PrintContacts(Cursor c)
{
ContentResolver cr = getContentResolver();
//---display the contact id and name and phone number----
if (c.moveToFirst()) {
do{
//---get the contact id and name
String contactID = c.getString(c.getColumnIndex(
ContactsContract.Contacts._ID));
String contactDisplayName =
c.getString(c.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME));
Log.v("Content Providers", contactID + ", " +
contactDisplayName);
String contactDisplayPhone = "";
//---get phone number---
int hasPhone =
c.getInt(c.getColumnIndex(
ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (hasPhone == 1) {
Cursor phoneCursor =
getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " +
contactID, null, null);
while (phoneCursor.moveToNext()) {
Log.v("Content Providers",
contactDisplayPhone = phoneCursor.getString(
phoneCursor.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER)));
}
phoneCursor.close();
}
contacts.add(new Contact(contactDisplayName, contactID, contactDisplayPhone));
} while (c.moveToNext());
}
}
public class Contact{
public String contactName = "";
public String contactID = "";
public String contactNumber = "";
public Contact(String name, String id, String number){
contactName = name;
contactID = id;
contactNumber = number;
}
}
public class MyClassAdapter extends ArrayAdapter<Contact> {
private class ViewHolder {
private TextView name;
private TextView id;
private TextView number;
}
public MyClassAdapter(Context context, int textViewResourceId, ArrayList<Contact> items) {
super(context, textViewResourceId, items);
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
convertView = LayoutInflater.from(this.getContext())
.inflate(R.layout.row_line, parent, false);
viewHolder = new ViewHolder();
viewHolder.name = (TextView) convertView.findViewById(R.id.contactName);
viewHolder.id = (TextView) convertView.findViewById(R.id.contactID);
viewHolder.number = (TextView) convertView.findViewById(R.id.contactNumber);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
Contact item = getItem(position);
if (item!= null) {
viewHolder.name.setText(item.contactName);
viewHolder.id.setText(item.contactID);
viewHolder.number.setText(item.contactNumber);
}
return convertView;
}
}
}
row_line.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView android:id="#+id/contactName"
android:textSize="16sp"
android:textStyle="bold"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView android:id="#+id/contactID"
android:textSize="16sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView android:id="#+id/contactNumber"
android:textSize="16sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
activity_provider2.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".Provider2Activity">
<ListView
android:id="#android:id/list"
android:layout_height="wrap_content"
android:layout_width="match_parent">
</ListView>
</RelativeLayout>
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 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 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";
}
}