I have made a custom list in which I am getting all the phone book contacts and showing them in my own list with a custom view. I save all the contacts (inculding the contacts id) in an arraylist. When I click on a list I want it open all the details of that contact in the default android manner. Please can some one tell me if this is possible or not.
my code is below for saving the contacts in my own list:
arraylist = new ArrayList<PhoneBookUserEntity>();
Cursor cursor = getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI, null, null, null, Phone.DISPLAY_NAME + " ASC");
if (cursor.getCount() > 0)
{
while (cursor.moveToNext())
{
PhoneBookUserEntity user = new PhoneBookUserEntity();
// Pick out the ID, and the Display name of the
// contact from the current row of the cursor
user.setId(cursor.getString(cursor.getColumnIndex(BaseColumns._ID)));
user.setPhoneBookName(cursor.getString(cursor.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME)));
String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
// if (Boolean.parseBoolean(hasPhone)) {
Cursor phones = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ user.getId(), null, null);
while (phones.moveToNext()) {
user.sePhoneNumber(phones.getString(phones.getColumnIndex( ContactsContract.CommonDataKinds.Phone.NUMBER)));
}
phones.close();
//}
// user.sePhoneNumber(cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
Cursor emails = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + user.getId(), null, null);
while (emails.moveToNext()) {
// This would allow you get several email addresses
user.setEmailAddress(emails.getString(emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA)));
}
emails.close();
user.setImageURI(getPhotoUri(user.getId()));
arraylist.add(user);
// Do something with the values you have,
// such as print them out or add to a list
//System.out.println("Current contact on this iteration is : " + name);
// This is where we query for Emails, Addresses etc
// Add snippets below into here, depending on what you need
}
}
cursor.close();
Try this
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI, String.valueOf(contactID));
intent.setData(uri);
context.startActivity(intent);
This should open the contacts card in android
Related
I am trying to fetch contacts from the phonebook in my Android application. But it fetches the contacts that are present only in the local phone storage. I need to fetch all the contacts including the ones synced to the device using various accounts like Google. That is currently not happening. I am using a RecyclerView to display the contacts fetched.
I have tried using https://github.com/mirrajabi/rx-contacts2 library for fetching asynchronously. But that doesn't include Google contacts as well. Then I tried using Android's built-in CotentResolver
Contact contact;
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
if (cursor != null) {
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
contact = new Contact(Long.parseLong(id));
contact.setDisplayName(name);
Cursor phoneCursor = contentResolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id},
null);
if (phoneCursor != null) {
if (phoneCursor.moveToNext()) {
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Set<String> phoneNumbers = new HashSet<>();
phoneNumbers.add(phoneNumber);
contact.setPhoneNumbers(phoneNumbers);
}
phoneCursor.close();
}
Cursor emailCursor = contentResolver.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{id}, null);
if (emailCursor != null) {
while (emailCursor.moveToNext()) {
String emailId = emailCursor.getString(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
}
emailCursor.close();
}
listContacts.add(contact);
}
}
}
cursor.close();
}
Currently, I am trying to fetch the contacts synchronously and it hangs up the main thread. It would be really helpful if you could suggest some ways to do that asynchronously. When doing so I also require a trigger to know when the task is completed.
Your code should work on all contacts synced to the device, including Google contacts (assuming the Google account is installed, and the contacts sync is enabled).
However, your code has some bugs, and can be greatly improved, currently for a device with 500 contacts, you are doing ~1000 queries.
All the data you need is on a single table called Data so you can get everything in a single quick query, see here:
Map<Long, Contact> contacts = new HashMap<>();
String[] projection = {Data.CONTACT_ID, Data.DISPLAY_NAME, Data.MIMETYPE, Data.DATA1};
String selection = Data.MIMETYPE + " IN ('" + Phone.CONTENT_ITEM_TYPE + "', '" + Email.CONTENT_ITEM_TYPE + "')";
Cursor cur = cr.query(Data.CONTENT_URI, projection, selection, null, null);
while (cur.moveToNext()) {
long id = cur.getLong(0);
String name = cur.getString(1);
String mime = cur.getString(2); // email / phone
String data = cur.getString(3); // the actual info, e.g. +1-212-555-1234
// get the Contact class from the HashMap, or create a new one and add it to the Hash
Contact contact;
if (contacts.containsKey(id)) {
contact = contacts.get(id);
} else {
contact = new Contact(id);
contact.setDisplayName(name);
// start with empty Sets for phones and emails
contact.setPhoneNumbers(new HashSet<>());
contact.setEmails(new HashSet<>());
contacts.put(id, contact);
}
switch (mime) {
case Phone.CONTENT_ITEM_TYPE:
contact.getPhoneNumbers().add(data);
break;
case Email.CONTENT_ITEM_TYPE:
contact.getEmails().add(data);
break;
}
}
cur.close();
Notes:
I've changed your listContacts to a HashMap called contacts so we can quickly find an existing contact
I've added setEmails, getPhoneNumbers and getEmails to your Contact class
I have developed a program that shows a list of contacts from my phone book.
For this I use the following code:
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI,
null,
ContactsContract.Contacts.HAS_PHONE_NUMBER + " = '1'",
null,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
if (cursor != null && cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI, String.valueOf(id));
Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + id,
null,
null);
if (phones != null) {
while (phones.moveToNext()) {
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contactList.add(new Contact(name, phoneNumber, id));
}
phones.close();
}
}
cursor.close();
}
adapter = new ContactAdapter(contactList, R.layout.contacts_list_item, getApplicationContext());
recyclerView.setAdapter(adapter);
Everything works, and the program displays all contacts from my phone book, but I want a certain number of contacts to be displayed. For example:
I open the program and load the first 50 contacts from the phone book, after scrolling, the next 50 contacts are loaded to the end of the list. and so on
Use below code that has limit cause. Replace your code with below
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI,
null,
ContactsContract.Contacts.HAS_PHONE_NUMBER + " = '1' ",
null,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " COLLATE LOCALIZED ASC LIMIT 10");
It will get first 10 records. And in pull to refresh implementation, get more records on call back event of pull to refresh. Hope this will help you
I assume the reason you want this is because loading all contacts is very slow.
The reason it's very slow is because you currently have 1 query per contact, so if a user has 500 contacts, you'll need to run 500 queries.
You can reduce the number of queries to just one, then I assume you won't need the limit thing.
String[] projection = { Phone.CONTACT_ID, Phone.DISPLAY_NAME, Phone.NUMBER };
Cursor phones = getContentResolver().query(Phone.CONTENT_URI, projection, null, null, Phone.DISPLAY_NAME + " ASC");
while (phones.moveToNext()) {
String name = phones.getString(1);
String phone = phones.getString(2);
Long id = phones.getLong(0);
contactList.add(new Contact(name, phone, id));
}
phones.close();
If you want to display only one item per contact, and not per phone, you can change your contactList field to be a HashMap<Long, Contact> instead of a List, and add newly found phones to an existing Contact object if it already exists in the Map.
Something like:
Contact contact = allContacts.get(id);
if (contact == null) {
contact = new Contact(name, phone, id);
allContacts.put(id, contact);
} else {
contact.addPhone(phone); // you'll need to implement this
}
I am trying to create an app which selects the contact from the contacts and display the name and number on the screen. Till now I have created activity to select the contact and the activity is successfully returning the contacts. It is successful in showing the Contact name. Now I have problem in showing the numbers in it. There are variety of solutions and I want the simplest one. All of them goes through complex methods which is hard for me to understand. I am unable to find a simple function that can display the number like ContactsContract.Contacts.DISPLAY_NAME
Here is my code!
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_contact);
Intent viewContact = getIntent();
String tempViewContact = viewContact.getStringExtra(MainActivity.contactUri);
Uri contactUri = Uri.parse(tempViewContact);
Cursor cursor;
cursor = getContentResolver().query(contactUri,null,null,null,null);
cursor.moveToFirst();
int indexName = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
int indexID = cursor.getColumnIndex(ContactsContract.Contacts._ID);
//Shows Contact name
String contactName = cursor.getString(indexName);
contact_name = (TextView) findViewById(R.id.contact_name);
contact_name.setText(contactName);
contact_num = (TextView) findViewById(R.id.contact_number);
//Now what to do ????
}
Here is a small snippet on how to collect contacts from the device
// Getting Content Resolver to Access Contact Details
ContentResolver cr = c.getContentResolver();
// Getting Cursor
Cursor cur1 = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
null, null, null);
// Checking CURSOR HAS DATA
if (cur1.getCount() > 0) {
// LOOPING THROUGH EVERY CONTACT
while (cur1.moveToNext()) {
// GETTING CONTACT ID
String id = cur1.getString(cur1
.getColumnIndex(ContactsContract.Contacts._ID));
// GETTING CONTACT NAME
String contactName = cur1
.getString(cur1
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String contactNumber = "";
// Ensuring number availablity
if (Integer
.parseInt(cur1.getString(cur1
.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
// Phone numbers are stored in another table
// Cursor for Phone Numbers
Cursor pCur = cr
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?", new String[] { id },
null);
// Has Number in Cursor - CHECK + LOOP
while (pCur.moveToNext()) {
// Checking Number Count for A SINGLE
// CONTACT
if (pCur.getCount() > 1) {
contactNumber = contactNumber
+ ","
+ pCur.getString(pCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
} else {
contactNumber = pCur
.getString(pCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
}
}
// LOGGING
Log.d("X", "ID:" + id + "\nName:" + contactName
+ "\nNumber:" + contactNumber);
Log.i("X", "--------------------------------");
include the below permission in the manifest
<uses-permission android:name="android.permission.READ_CONTACTS" />
If you want to show the name and the contact number in a list, then follow the below steps
1) Build a model class with two fields name and contact say ContactModel
2) Make a ContactModel List and add each model into the list.
3) Finally attach the data to the listView using a custom adapter.
I want to filter what numbers I am getting from Android based on which contacts the user chose to display in his contact book. (For example only contacts saved on the device when all other contacts are excluded)
I read here that you can do this by using
Uri queryUri = ContactsContract.Contacts.CONTENT_URI;
I use following code to read the contacts and I allways get every contact, phone, SIM, etc..
//https://stackoverflow.com/questions/16651609/how-to-display-phone-contacts-only-exclude-sim-contacts
// http://www.higherpass.com/Android/Tutorials/Working-With-Android-Contacts/1/
ContentResolver cr = currentActivity.getContentResolver();
Uri queryUri = ContactsContract.Contacts.CONTENT_URI;
Cursor cur = cr.query(queryUri,
null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) { //Are there still contacts?
//See if the contact has at least one number
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
String id = cur.getString( cur.getColumnIndex(ContactsContract.Contacts._ID) );
String name = cur.getString( cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME) );
ArrayList<String> numbers = new ArrayList<String>();
//Read numbers:
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
numbers.add( pCur.getString(
pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)) );
Log.e("Contactbook", "The latest added number is: " + numbers.get(numbers.size()-1) );
}
pCur.close();
}
}
}
What am I missing? This code still gives me both SIM and phone contacts to the log.
Edit: To clarifify, in the contactbook you got the "Display options". In there ist the "select contacts to display"-option, and I want to read the contacts that are shown based on the users choice there. So if a user choses to show only SIM-contacts, read only SIM-contacts, if he choses to only show Phone-Contacts, show onyl phone contacts etc...
Try with following "selection".
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = ?";
From Android docs:
public static final String IN_VISIBLE_GROUP: An indicator of whether this contact is supposed to be visible in the UI. "1" if the contact has at least one raw contact that belongs to a visible group; "0" otherwise.
This should be your "selection" argument in query API.
Update: I tried below code on Android-2.3(I know it is old device, but right now Don't have newer device with me).
final ContentResolver cr = getContentResolver();
String[] projection = new String[] { ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME };
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = ?" ;
String[] Args = { "1" };
final Cursor contacts = cr.query(
ContactsContract.Contacts.CONTENT_URI, projection,
selection,Args ,
null);
This could be a long operation (depending on no. of contacts), hence you should use CursorLoader class (A loader that queries the ContentResolver and returns a Cursor) for this.
cursorLoader.loadInBackground();
This will be called on a worker thread to perform the actual load and to return the result of the load operation.
You can easily create two Arrays for each kind of contacts
ArrayList<String> simContacts = new ArrayList<>();
//get all sim contacts
Uri simUri = Uri.parse("content://icc/adn");
Cursor cursorSim = getContext().getContentResolver().query(simUri, null, null, null, null);
while (cursorSim.moveToNext()) {
simContacts.add(cursorSim.getString(cursorSim.getColumnIndex("name")));
}
}
ArrayList<String> allContacts = new ArrayList<>();
//get all contacts
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if (cursor != null && cursor.getCount() > 0) {
while (!cursor.isAfterLast()) {
String phoneNumber = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER));
String displayNameColumn = Utils.hasHoneycomb() ? ContactsContract.Contacts.DISPLAY_NAME_PRIMARY : ContactsContract.Contacts.DISPLAY_NAME;
String displayName = cursor.getString(cursor.getColumnIndexOrThrow(displayNameColumn));
//check if simContacts Array contains this particular name
if (!simContacts.contains(displayNameColumn){
allContacts.add(displayNameColumn);
}
}
}
This is just a working example,of course you can modify to your needs.You can parse more contact fields and make more complication queries.
I use the following code to retrieve all phone number from contacts.
Cursor c = context.getContentResolver().query(
Data.CONTENT_URI,
new String[] { Phone.NUMBER },
Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE
+ "'", null, null);
It works perfectly in my Android phone.
But some users say my app doesn't get all phone numbers from contacts and just part of them. I can't figure out the reason.. why?
This will get the cursor holding base contact data, and will loop through the phone numbers the contact has, can have multiple.
Uri uri = data.getData();
Cursor cursor=ctx.getContentResolver().query(uri, null, null, null, null);
while (cursor.moveToNext()) {
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (Boolean.parseBoolean(hasPhone)) {
// You know have the number so now query it like this
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId,
null, null);
while (phones.moveToNext()) {
String phoneNumber = phones.getString(
phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
phones.close();
}
}