ListView of Contacts - android

I want to have a ListView of my contacts.
I use Google sample code.
The problem is that I get the same contacts over and over again:
Jim
Jim
Jim
Jim
Jim
Anna
Anna
Anna
Anna
...
How can I get a DISTINCT list of my contacts?
public class ContactsListView extends ListActivity
implements LoaderManager.LoaderCallbacks<Cursor> {
SimpleCursorAdapter mAdapter;
static final String[] PROJECTION = new String[] {ContactsContract.Data._ID,
ContactsContract.Data.DISPLAY_NAME};
static final String SELECTION = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '"
+ ("1") + "'";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create a progress bar to display while the list loads
ProgressBar progressBar = new ProgressBar(this);
progressBar.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,Gravity.CENTER));
progressBar.setIndeterminate(true);
getListView().setEmptyView(progressBar);
// Must add the progress bar to the root of the layout
ViewGroup root = (ViewGroup) findViewById(android.R.id.content);
root.addView(progressBar);
// For the cursor adapter, specify which columns go into which views
String[] fromColumns = {ContactsContract.Data.DISPLAY_NAME};
int[] toViews = {android.R.id.text1}; // The TextView in simple_list_item_1
// Create an empty adapter we will use to display the loaded data.
// We pass null for the cursor, then update it in onLoadFinished()
mAdapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1, null,
fromColumns, toViews, 0);
setListAdapter(mAdapter);
// Prepare the loader. Either re-connect with an existing one,
// or start a new one.
getLoaderManager().initLoader(0, null, this);
}
// Called when a new Loader needs to be created
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// Now create and return a CursorLoader that will take care of
// creating a Cursor for the data being displayed.
return new CursorLoader(this, ContactsContract.Data.CONTENT_URI,
PROJECTION, SELECTION, null, ContactsContract.Contacts.DISPLAY_NAME
+ " COLLATE LOCALIZED ASC");
}
// Called when a previously created loader has finished loading
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
// Swap the new cursor in. (The framework will take care of closing the
// old cursor once we return.)
mAdapter.swapCursor(data);
}
// Called when a previously created loader is reset, making the data unavailable
public void onLoaderReset(Loader<Cursor> loader) {
// This is called when the last Cursor provided to onLoadFinished()
// above is about to be closed. We need to make sure we are no
// longer using it.
mAdapter.swapCursor(null);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id)
{
// String itemValue = (String) l.getItemAtPosition(position);
}
}

In your line with String[] fromColumns = {ContactsContract.Data.DISPLAY_NAME};, instead of
ContactsContract.Data.DISPLAY_NAME
try
ContactsContract.Contacts.DISPLAY_NAME_PRIMARY
In the documentation you can read that Data are entries representing any number or email address or whatever, while Contacts are entries representing one person.

try this code
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '"
+ ("1") + "'";
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME
+ " COLLATE LOCALIZED ASC";
cur = context.getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI, projection, selection
+ " AND " + ContactsContract.Contacts.HAS_PHONE_NUMBER
+ "=1", null, sortOrder);// this query only return contacts which had phone number and not duplicated

for your code))
// Called when a new Loader needs to be created
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// Now create and return a CursorLoader that will take care of
// creating a Cursor for the data being displayed.
return new CursorLoader(this, ContactsContract.Data.CONTENT_URI,
projection, selection
+ " AND " + ContactsContract.Contacts.HAS_PHONE_NUMBER
+ "=1", null, sortOrder);
}

Use set instead of List. Set holds only unique elements, so duplicate elements are not present in resultant collection.

Related

How to get some informations of a contact by using cursor loader?

I want to get: id, name, phone number and company of all contacts which stored in default contact of the phone. After that, I want to display them into list view.
I use cursor loader to do that. BUT, i have just get id and name of each contact. I CAN NOT get phone number & company. You can see all my code below.
I think I may be wrong at: PROJECTION & SELECTION (?)
What about your opinion?? Could you show me what my error is?
public class MainActivity extends ListActivity implements LoaderManager.LoaderCallbacks<Cursor>{
final Context context = this;
protected Intent intent;
protected TextView contactId;
protected ListView lv;
protected EditText inputSearch;
protected SimpleAdapter adapter;
SimpleCursorAdapter curAdapter;
public MatrixCursor extras;
SimpleCursorAdapter mAdapter;
static final String[] PROJECTION = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Organization.DATA};
static final String SELECTION = "("+
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + ContactsContract.Contacts._ID + " AND " +
ContactsContract.Data.CONTACT_ID + " = " + ContactsContract.Contacts._ID + " AND " +
ContactsContract.Data.MIMETYPE + " = " + ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE +
")";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] fromColumns = {ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Organization.DATA};
int[] toViews = { R.id.contactId,
R.id.contactName,
R.id.phone,
R.id.company};
mAdapter = new SimpleCursorAdapter(this,
R.layout.view_contact_entry, null,
fromColumns, toViews, 0);
setListAdapter(mAdapter);
getLoaderManager().initLoader(0, null, this);
}
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return new CursorLoader(this, ContactsContract.Contacts.CONTENT_URI,
PROJECTION, SELECTION, null, "DISPLAY_NAME ASC");
}
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
mAdapter.swapCursor(data);
}
public void onLoaderReset(Loader<Cursor> loader) {
mAdapter.swapCursor(null);
}
}
OK. And here is all information in logcat:
https://lh5.googleusercontent.com/-rXZ0iSq_CEg/Uf9bk-CmwBI/AAAAAAAAAVQ/SvieJesBqqQ/s800/Untitled.png
Try changing each ContactsContract.Contacts._ID for ContactsContract.CommonDataKinds.Phone._ID
and ContactsContract.Contacts.DISPLAY_NAME for ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME

Using CursorLoader to get emails causes duplication of emails

I am trying to get email ids of uses contacts. For that I am using Cursor Loader. There is one problem I am getting duplicate email ids also. How to remove email duplicacy. Should I use raw query "SELECT DISTINCT" instead of using CursorLoader or there is some other solution?
#Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
String[] projection = new String[] { ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.CommonDataKinds.Email.DATA};
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP +"='1' AND " + Email.DATA +" IS NOT NULL AND " + Email.DATA +" != \"\" " ;
//showing only visible contacts
String[] selectionArgs = null;
return new CursorLoader(this, ContactsContract.CommonDataKinds.Email.CONTENT_URI, projection, selection, selectionArgs, sortOrder);
}
I recently ran into this problem. It appears that the CursorLoader does not have an implementation of "DISTINCT". My workaround adds a few lines to the onLoadFinish method and extends the BaseAdapter to accept a List parameter:
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String projection[] = {
CommonDataKinds.Phone._ID,
CommonDataKinds.Phone.DISPLAY_NAME,
};
String select = "((" + CommonDataKinds.Phone.DISPLAY_NAME + " NOTNULL) and " + CommonDataKinds.Phone.HAS_PHONE_NUMBER + " > 0)";
String sort = CommonDataKinds.Phone.DISPLAY_NAME + " ASC";
CursorLoader loader = new CursorLoader(
mContext,
CommonDataKinds.Phone.CONTENT_URI,
projection,
select,
null,
sort
);
return loader;
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
List<String> displayNames = new ArrayList<String>();
cursor.moveToFirst();
while(!cursor.isAfterLast()){
String name = cursor.getString(cursor.getColumnIndex(CommonDataKinds.Phone.DISPLAY_NAME));
if(!displayNames.contains(name))
displayNames.add(name);
cursor.moveToNext();
}
mAdapter.swapCursor(displayNames);
}
Here is my BaseAdapter class:
public class AdapterAddContacts extends BaseAdapter{
private List<String> mData = new ArrayList<String>();
private Context mContext;
public AdapterAddContacts(Context context,List<String> displayNames){
mData = displayNames;
mContext = context;
}
#Override
public int getCount() {
if(mData != null)
return mData.size();
else
return 0;
}
#Override
public Object getItem(int pos) {
return mData.get(pos);
}
#Override
public long getItemId(int id) {
return id;
}
#Override
public View getView(int pos, View convertView, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View view = inflater.inflate(R.layout.entry_add_contacts,parent,false);
String data = mData.get(pos);
TextView textName = (TextView)view.findViewById(R.id.my_contacts_add_display_name);
textName.setText(data);
textName.setTag(data);
return view;
}
public void swapCursor(List<String> displayNames){
mData = displayNames;
this.notifyDataSetChanged();
}
You should be able to modify this specifically for your needs.
Inspired by #mars, I have a solution that does not need a modification of the adapter. The idea is to delete the duplicates of the cursor; as there is no way to do it, we create a new cursor whithout the duplicates.
All the code is in onLoadFinished:
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
MatrixCursor newCursor = new MatrixCursor(PROJECTION); // Same projection used in loader
if (cursor.moveToFirst()) {
String lastName = "";
do {
if (cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)).compareToIgnoreCase(lastName) != 0) {
newCursor.addRow(new Object[]{cursor.getString(0), cursor.getString(1), cursor.getString(2) ...}); // match the original cursor fields
lastName =cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
}
} while (cursor.moveToNext());
}
mContactsAdapter.swapCursor(newCursor);
}
I used a small hack in my project - an SQL injection, like that:
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return new CursorLoader(
this,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[] {
"DISTINCT "+ MediaStore.Images.Media.BUCKET_ID,
MediaStore.Images.Media.BUCKET_DISPLAY_NAME},
null, null, null);
}
This code returns only bundle names and their IDs from Gallery.
So, I'd rewrite your code like that:
#Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
String[] projection = new String[] {
"DISTINCT " + ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Email.DATA};
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP +"='1' AND " + Email.DATA +" IS NOT NULL AND " + Email.DATA +" != \"\" " ;
//showing only visible contacts
String[] selectionArgs = null;
return new CursorLoader(this, ContactsContract.CommonDataKinds.Email.CONTENT_URI, projection, selection, selectionArgs, sortOrder);
}
You can put setDistinct in your content provider.
#Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
...
final SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setDistinct(true);
If you are worried about performance and don't want to play around with cursor again in onLoadFinished(), then there is a small hack
I combined following two solutions from SO.
select distinct value in android sqlite
CursorLoader with rawQuery
And here is my working solution:
#Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
String tableName;
/*
* Choose the table to query and a sort order based on the code returned
* for the incoming URI.
*/
switch (uriMatcher.match(uri)) {
case NOTIFICATION:
tableName = NOTIFICATIONS_TABLE_NAME;
break;
case NOTIFICATION_TIMESTAMP:
Cursor cursor = db.query(true, NOTIFICATIONS_TABLE_NAME, projection, selection, selectionArgs, TIMESTAMP, null, sortOrder, null);
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
case DOWNLOAD:
tableName = DOWNLOADS_TABLE;
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
if (selection != null) {
selection = selection + "=?";
}
Cursor cursor = db.query(tableName, projection, selection, selectionArgs, null, null, sortOrder);
// Tell the cursor what uri to watch, so it knows when its source data
// changes
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
}
If you see in this case Table name is same is first 2 cases but i created a dummy Uri to achieve this. May not be a very good approach but works perfectly.
I found a solution
Use DISTINCT keyword in selection Array.
String[] projection = new String[] { ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME, "DISTINCT" + ContactsContract.CommonDataKinds.Email.DATA};

Reading contacts with loader manager

Im trying to make use of the LoaderManager and the CursorLoader to read the phone numbers of contacts. I'm able to read the contact's display name but Im not sure how to read the phone numbers. Any guidance would be much appreciated.
// These are the Contacts rows that we will retrieve.
static final String[] CONTACTS_SUMMARY_PROJECTION = new String[] {
Contacts._ID, Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER };
// This is the Adapter being used to display the list's data.
SimpleCursorAdapter mAdapter;
// If non-null, this is the current filter the user has provided.
String mCurFilter;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Give some text to display if there is no data. In a real
// application this would come from a resource.
setEmptyText("No phone numbers");
// Create an empty adapter we will use to display the loaded data.
mAdapter = new SimpleCursorAdapter(getActivity(),
android.R.layout.simple_list_item_2, null, new String[] {
Contacts.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER },
new int[] { android.R.id.text1, android.R.id.text2 }, 0);
setListAdapter(mAdapter);
// Start out with a progress indicator.
setListShown(false);
// Prepare the loader. Either re-connect with an existing one,
// or start a new one.
getLoaderManager().initLoader(0, null, this);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Log.i("FragmentComplexList", "Item clicked: " + id);
}
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// This is called when a new Loader needs to be created. This
// sample only has one Loader, so we don't care about the ID.
// First, pick the base URI to use depending on whether we are
// currently filtering.
Uri baseUri;
if (mCurFilter != null) {
baseUri = Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI,
Uri.encode(mCurFilter));
} else {
baseUri = Contacts.CONTENT_URI;
}
// Now create and return a CursorLoader that will take care of
// creating a Cursor for the data being displayed.
String select = "((" + Contacts.DISPLAY_NAME + " NOTNULL) AND ("
+ Contacts.HAS_PHONE_NUMBER + "=1) AND ("
+ Contacts.DISPLAY_NAME + " != '' ))";
return new CursorLoader(getActivity(), baseUri,
CONTACTS_SUMMARY_PROJECTION, select, null,
Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
}
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
// Swap the new cursor in. (The framework will take care of closing the
// old cursor once we return.)
mAdapter.swapCursor(data);
// The list should now be shown.
if (isResumed()) {
setListShown(true);
} else {
setListShownNoAnimation(true);
}
}
public void onLoaderReset(Loader<Cursor> loader) {
// This is called when the last Cursor provided to onLoadFinished()
// above is about to be closed. We need to make sure we are no
// longer using it.
mAdapter.swapCursor(null);
}
Try this.. this worked for me!
// This is the Adapter being used to display the list's data.
SimpleCursorAdapter mAdapter;
// If non-null, this is the current filter the user has provided.
String mCurFilter;
#Override public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Give some text to display if there is no data. In a real
// application this would come from a resource.
setEmptyText("No phone numbers");
// We have a menu item to show in action bar.
setHasOptionsMenu(true);
// Create an empty adapter we will use to display the loaded data.
mAdapter = new SimpleCursorAdapter(getActivity(),
android.R.layout.simple_list_item_1, null,
new String[] { ContactsContract.CommonDataKinds.Phone.NUMBER, },
new int[] { android.R.id.text1}, 0);
setListAdapter(mAdapter);
// Start out with a progress indicator.
setListShown(false);
// Prepare the loader. Either re-connect with an existing one,
// or start a new one.
getLoaderManager().initLoader(0, null, this);
}
#Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Place an action bar item for searching.
MenuItem item = menu.add("Search");
item.setIcon(android.R.drawable.ic_menu_search);
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
View searchView = SearchViewCompat.newSearchView(getActivity());
if (searchView != null) {
SearchViewCompat.setOnQueryTextListener(searchView,
new OnQueryTextListenerCompat() {
#Override
public boolean onQueryTextChange(String newText) {
// Called when the action bar search text has changed. Update
// the search filter, and restart the loader to do a new query
// with this filter.
mCurFilter = !TextUtils.isEmpty(newText) ? newText : null;
getLoaderManager().restartLoader(0, null, CursorLoaderListFragment.this);
return true;
}
});
item.setActionView(searchView);
}
}
#Override public void onListItemClick(ListView l, View v, int position, long id) {
// Insert desired behavior here.
Log.i("FragmentComplexList", "Item clicked: " + id);
}
// These are the Contacts rows that we will retrieve.
static final String[] CONTACTS_SUMMARY_PROJECTION = new String[] {
ContactsContract.CommonDataKinds.Phone._ID,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER,
};
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// This is called when a new Loader needs to be created. This
// sample only has one Loader, so we don't care about the ID.
// First, pick the base URI to use depending on whether we are
// currently filtering.
Uri baseUri;
if (mCurFilter != null) {
baseUri = Uri.withAppendedPath(ContactsContract.CommonDataKinds.Phone.CONTENT_FILTER_URI, Uri.encode(mCurFilter));
} else {
baseUri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
}
// Now create and return a CursorLoader that will take care of
// creating a Cursor for the data being displayed.
String select = "((" + ContactsContract.Contacts.DISPLAY_NAME + " NOTNULL) AND ("
+ ContactsContract.Contacts.DISPLAY_NAME + " != '' )" + "AND ("+ContactsContract.Contacts.HAS_PHONE_NUMBER +" != '0'"+"))";
return new CursorLoader(getActivity(), baseUri,
CONTACTS_SUMMARY_PROJECTION, null, null,
null + " COLLATE LOCALIZED ASC");
}
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
// Swap the new cursor in. (The framework will take care of closing the
// old cursor once we return.)
mAdapter.swapCursor(data);
// The list should now be shown.
if (isResumed()) {
setListShown(true);
} else {
setListShownNoAnimation(true);
}
}
public void onLoaderReset(Loader<Cursor> loader) {
// This is called when the last Cursor provided to onLoadFinished()
// above is about to be closed. We need to make sure we are no
// longer using it.
mAdapter.swapCursor(null);
}
}

Retrieving phone number from contact id : android

I'm trying to get contact data once a contact name has been clicked from my list view. As per the code below, I can log successfully the ID of my contact, but haven't managed to use the ContactsContract to retrieve the data. What's the best way to do this? (have tried Retrieve Contact Phone Number From URI in Android to not much avail)
EDIT 2 : Fixed code, now works
public void onCreate(Bundle savedInstanceState)
{
Log.v(TAG, "Activity State: onCreate()");
super.onCreate(savedInstanceState);
setContentView(R.layout.contact_manager);
mContactList = (ListView) findViewById(R.id.contactList);
populateContactList();
mContactList.setOnItemClickListener(new OnItemClickListener() {
String strid = Long.toString(id);
Cursor result = managedQuery(ContactsContract.Contacts.CONTENT_URI, null, ContactsContract.Contacts._ID +" = ?", new String[]{strid}, null);
if (result.moveToFirst()) {
Cursor c = getContentResolver().query(Data.CONTENT_URI,
new String[] {Data._ID, Phone.NUMBER, Phone.TYPE, Phone.LABEL},
Data.RAW_CONTACT_ID + "=?" + " AND "
+ Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'",
new String[] {String.valueOf(strid)}, null);
if(c.moveToFirst()){
int phoneColumn = c.getColumnIndex("data1");
String phoneNumber = c.getString(phoneColumn);
Log.d("DATA",phoneNumber);
}
}
});
}
EDIT 1 : forgot some important stuff. The code is adapted from the ContactManager example from the Android dev site.
/**
* Populate the contact list based on account currently selected in the account spinner.
*/
private void populateContactList() {
// Build adapter with contact entries
Cursor cursor = getContacts();
String[] fields = new String[] {
ContactsContract.Data.DISPLAY_NAME
};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.contact_entry, cursor,
fields, new int[] {R.id.contactEntryText});
mContactList.setAdapter(adapter);
}
/**
* 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.Contacts.CONTENT_URI;
String[] projection = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME
};
String selection = null;
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
return managedQuery(uri, projection, selection, selectionArgs, sortOrder);
}
Assuming you have a valid contactID, you can do this:
Cursor result = managedQuery(ContactsContract.Contacts.CONTENT_URI, null,
ContactsContract.Contacts._ID +" = ?",
new String[]{contactID}, null);
if (result.moveToFirst()) {
for(int i=0; i< result.getColumnCount(); i++){
Log.i("CONTACTSTAG", result.getColumnName(i) + ": "
+ result.getString(i));
}
}
You will have to change the ContactsContract.Contacts.CONTENT_URI and the where clause to the table that you are querying. The above code will print out a bunch of general info about a contact.

how to get contact number into Text view?

this is is the code i have but everytime i click on the contact it force closes. and is there a code so that when i get the contact it adds it into a text view?
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.main2);
// Obtain handles to UI objects
mAddAccountButton = (Button) findViewById(R.id.AddContact);
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
mAddAccountButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d(TAG, "mAddAccountButton clicked");
launchContactAdder();
}
});
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();
}
/**
* Populate the contact list based on account currently selected in the account spinner.
*/
private void populateContactList() {
// Build adapter with contact entries
Cursor cursor = getContacts();
String[] fields = new String[] {
ContactsContract.Data.DISPLAY_NAME
};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.main, cursor,
fields, new int[] {R.id.TextView01});
mContactList.setAdapter(adapter);
}
/**
* 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.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);
}
/**
* Launches the ContactAdder activity to add a new contact to the selected account.
*/
protected void launchContactAdder() {
Intent i = new Intent(this,Class1.class);
startActivity(i);
}
}
based on my experience with the contacts list, you need to design your query based on what is available. In 1.6 there was the simplicity of one table with all the information. However; with the dawn of 2.0, they introduced two tables. Where you get the ID from one table and the query based on this ID to find the phone number. To illustrate this here is a piece of sample code that worked for me, although i'm having some minor problems where some contacts won't return a phone number 2/70 although all 70 users have an ID and Phone number. I hope it helps:
// look up contact via name
String name = contacts.getItem(arg1);
Uri lookup = Uri.withAppendedPath(
ContactsContract.Contacts.CONTENT_FILTER_URI, name);
// look up id
Cursor c = getContentResolver().query(lookup, null, null, null, null);
String id = null;
int id_index = c.getColumnIndexOrThrow(ContactsContract.Contacts._ID);
if (c.moveToFirst())
id = c.getString(id_index);
else
Toast.makeText(getApplicationContext(), "Friend not found",
Toast.LENGTH_SHORT).show();
c.close();
// use id if not null, to find contact's phone number / display name
if (id != null) {
String where = ContactsContract.Data.CONTACT_ID + " = " + id
+ " AND " + ContactsContract.Data.MIMETYPE + " = '"
+ ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE
+ "'";
c = getContentResolver().query(ContactsContract.Data.CONTENT_URI,
null, where, null, null);
c.moveToFirst();
int iname = c
.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME);
int iphone = c
.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER);
if (c.getCount() > 0) {
_friend.setName(c.getString(iname));
_friend.setPhone(c.getString(iphone));
If you have any further questions, please don't hesitate to ask, I'll do my best to answer them. For what I can tell without a log cat is that you are attempting a look up of the phone number the proper table structure for the query. If you try to access information from a query that returned 0 rows, then you'll get an exception. Please read that error and display it.
You have to use for all Email, Phone Numbers, Web-Address etc.
Example:
Linkify.addLinks(textView, Linkify.WEB_URLS);
Parameter: textview which you are adding string
Which thing you want to track email,phone or web
For more details:
http://developer.android.com/reference/android/text/util/Linkify.html
Note: for this you no need to implement any onClick etc. Linkif automatically manage it.

Categories

Resources