I want to fetch contacts stored in Phone but getting problem - android

i am using following code in order to fetch contacts from Phone
i am getting names but not number , help me to find out other fields of contacts.
public class DialActivity extends Activity {
private ListView mContactList;
public String[] fields;
public Cursor cursor;
public boolean mShowInvisible;
public Uri uri;
public String[] projection;
public String[] selectionArgs;
public String selection;
public String sortOrder;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mContactList = (ListView) findViewById(R.id.ListView01);
// 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.listrow, 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);
}
}
In the above code i am using a custom ListRow layout and showing the contact name in each row, but want to populate a list which has names and corresponding number so that i can make a call on those number by clicking on that listItem. I know how to make call but i am not having the numbers.

ContactsContract.Contacts doesn't contain the phone number but you have the id of the contacts so you can now query ContactsContract.Data to get the phone number. A sample query can be found at the documentation: http://developer.android.com/reference/android/provider/ContactsContract.Data.html

Related

ListView of Contacts

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.

Get the company name of contact in android?

Hi i am doing a app on contact app i got the contact id and the Display name using the below code now what i want is the company name alone with the contact id and the display name.how can i get the Company name?
private void populateContactList() {
// Build adapter with contact entries
Cursor cursor = getContacts();
fields = new String[] { ContactsContract.Data.DISPLAY_NAME,
ContactsContract.Contacts._ID};
contactqueryAdaptor = new Contactquery_adaptor(this, R.layout.row,
cursor, fields, new int[] { R.id.applese });
}
//getContacts()
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);
}
According to this: Get company name form Content Provider in android using new API's, you'll need to query the ContactsContract.Data and use these aliases http://developer.android.com/reference/android/provider/ContactsContract.CommonDataKinds.Organization.html

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.

Android: Set contact photo in a ListView with name and number

I'm creating an app that needs to display the phone contacts with its photo, name and number. I've created a ListView and can show contacts and numbers with a generic photo, but I can't show contat's picture. This is my code:
Cursor cursor = getContacts();
String[] fields = new String[] {Contacts.DISPLAY_NAME, Phone.NUMBER};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.contact_entry, cursor,
fields, new int[] {R.id.contactEntryText, R.id.contactEntryNumber});
mContactList.setAdapter(adapter);
private Cursor getContacts()
// Run query
Uri uri = Phone.CONTENT_URI;
String[] projection = new String[] {
Contacts._ID,
Contacts.DISPLAY_NAME,
Phone.NUMBER,
Contacts.PHOTO_ID
};
//String selection = Contacts.HAS_PHONE_NUMBER + "='1'";
String selection = null;
String[] selectionArgs = null;
String sortOrder = Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
return managedQuery(uri, projection, selection, selectionArgs, sortOrder);
}
How can I attach the contact's picture in the SimpleCursorAdapter? Is there another?
Thank you very much.
I figured it out. If someone had the same problem, this is how i did it:
In an activity that extends ListActivity:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Cursor names = getNamesAndPictures();
names.moveToFirst();
ListAdapter adapter = new MySimpleCursorAdapter(this, R.layout.contacts,
names, new String[] {Phones.NAME, Phones.NUMBER}, new int[] {
R.id.Nombre, R.id.Numero});
setListAdapter(adapter);
startManagingCursor(names);
Log.i(DEBUG_TAG, "Mi numero: " + miNumeroTelefono());
}
public Cursor getNamesAndPictures(){
String[] projection = new String[] {
Phones.NUMBER,
Phones.PERSON_ID,
People.NAME,
People._ID
};
String selection = Phones.NAME + "!='null'";
String sortOrder = Phones.NAME + " COLLATE LOCALIZED ASC";
Cursor cursor = managedQuery(Phones.CONTENT_URI, projection, selection, null, sortOrder);
return cursor;
}
In a custom adapter:
public class MySimpleCursorAdapter extends SimpleCursorAdapter {
...
#Override
public void bindView(View view, Context context, Cursor cursor) {
ImageView imageView = (ImageView) view.findViewById(R.id.Foto);
int id = cursor.getColumnIndex(Phones.PERSON_ID);
Uri uri = ContentUris.withAppendedId(Phones.CONTENT_URI, cursor.getLong(id));
String uriPhoto = uri.toString();
String uriPeople = uriPhoto.replace("phones", "people");
Uri uriFinal = Uri.parse(uriPeople);
Bitmap bitmap = People.loadContactPhoto(context, uriFinal, R.drawable.avatar02, null);
imageView.setImageBitmap(bitmap);
super.bindView(view, context, cursor);
}
}
I know it is a very old question but so is the answer as few things in this solution have now been deprecated. As the question showed up in searches while I was looking for similar solution, I though I will add my two cents here...
I have created a simple contacts list with their names and photos from ContactsContract.
Please check my answer at... https://stackoverflow.com/a/37710199/1209544

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