How to force refresh on CallLog.Calls.CACHED_NAME column? - android

My goal is to collect all unknown phone numbers from the Call Log.
This can be achieved by the following code:
private static final String[] CALLOG_PROJECTION = {CallLog.Calls._ID,
CallLog.Calls.CACHED_NAME, CallLog.Calls.NUMBER};
private static final String CALLOG_WHERE = CallLog.Calls.CACHED_NAME + " is null";
Cursor c = getContentResolver().query(CallLog.Calls.CONTENT_URI, CALLOG_PROJECTION,
CALLOG_WHERE, null, CallLog.Calls.DATE + " DESC");
This works well, but after i've created a contact from an unknown number, the result of the query still contains the unknown number.
If i open the Call Log activity window, i can see as the number changes to the name of the contact within a few seconds. So, the activity refreshes the CACHED_NAME column.
My question is, how can i programatically refresh (actualize) the Call Log ?

I landed on this question looking for ways to optimize what you're trying to do. Instead of using cached_name, I queried the Phone content provider for every number to get the actual name, but this led to performance issues.
I noticed that the stock application refreshes the list when a change occurred, as you did.
I'm going to implement a ContentObserver on the Phones table and update my name when that happens, I'll post if it works.
EDIT
I was checking the (Google's) Contacts app source code and they basically show the list with the CACHED_NAME first and, after the list is displayed, they check (on the background) if there were any changes to the contacts details. If there were any, they update the CallLog record and the list.
Basically, I've implemented something similar and it works. There were some performance issues when you scrolled the list while it was checking on the background for changes, because in a CallLog there are a lot of repeated numbers. So basically you just have to verify if those numbers are already being checked out.
Hope it helps!

Related

Why is ContentResolver.query() returning duplicate entries from contacts?

So I'm reading in these contacts using Android's native implementation, using a test phone with about 1,056 contacts on it. The problem I'm having is that it's rather slow, so I'm logging the outcomes of my cursor.moveToNext(), and seeing that it's reading in contacts past the last in an overlapping, duplicating fashion. It does, however, have previous logic implemented so the app compares the hashed version of this list of entries to the previously saved one every second... which eventually brings the entries back to the correct value, order, and contents. However, using the code below, at worst it's pulling the entire contact list AGAIN, and then putting it in there with the same list (essentially reads the same address book twice and reads it in, doubling entries). This gets worse the larger your contact list is (smaller books, like this Galaxy I have with 9 contacts, don't seem to be affected; whereas my phone with about 106 is slightly, and this tester with 1,053 significantly) with the larger phones I've tested taking upwards of a minute and a half to two minutes before it's fully updated, accurate, and done.
What's confusing is that it somehow, even after all this duplication, the check manages to come back and be exactly what it was supposed to be (i.e 1,053 contact phone I see it adding the 2,106th row, then it immediately loads the proper 1,053 contact book).
Here's how my cursor is defined:
Cursor c = mContext.getContentResolver().query(addressBookURI,
CONTACTS_QUERY_PROJECTION, CONTACTS_QUERY_SELECTION, null, CONTACTS_QUERY_SORT);
Here's each of the components of said Cursor "c":
private static final Uri addressBookURI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI.buildUpon().appendQueryParameter(ContactsContract.REMOVE_DUPLICATE_ENTRIES, "1").build();
private static final String[] CONTACTS_QUERY_PROJECTION = {
ContactsContract.Data.CONTACT_ID,
ContactsContract.Contacts.HAS_PHONE_NUMBER,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Data.DATA1,
ContactsContract.Data.DATA2,
"account_name"
};
private static final String CONTACTS_QUERY_SELECTION = "in_default_directory=1 and has_phone_number=1 and mimetype='vnd.android.cursor.item/phone_v2'";
private static final String CONTACTS_QUERY_SORT = "contact_id ASC";
Processing the Cursor "c"'s reads:
List<String[]> entries = new ArrayList<>();
while (c.moveToNext()) {
String id = c.getString(0);
String name = c.getString(2);
String phone = c.getString(3);
String type = c.getString(4);
String account_name = c.getString(5);
Log.d(sTag, "contact:row:" + id + ":" + name + ":" + phone + ":" + type + ":" +
account_name);
entries.add(new String[]{id, name, phone, type});
It's in that Log.d() statement where I can see duplicates of contacts, wherein the only difference between the original contact and follow-up duplicates is the "id" variable (keeps increasing, period).
For example (if it happened with smaller amounts of contacts; all values are made up):
contact:row:1:Maurine Lastpass:4145737719:3:D8:0B:9A:CC:88:BF
contact:row:2:Blondell Sosig:4013008122:3:D8:0B:9A:CC:88:BF
contact:row:3:Amber Altingle:8885554422:2:D8:0B:9A:CC:88:BF
contact:row:4:Frank Helgenson:8885554422:2:D8:0B:9A:CC:88:BF
contact:row:5:Hiro Xin:8885554422:2:D8:0B:9A:CC:88:BF
contact:row:6:Baley Balix:6316773675:2:D8:0B:9A:CC:88:BF
contact:row:7:Henry Halgor:6316773675:2:D8:0B:9A:CC:88:BF
contact:row:8:Hammy Xevronic:6316773675:2:D8:0B:9A:CC:88:BF
contact:row:9:Maurine Lastpass:4145737719:3:D8:0B:9A:CC:88:BF
contact:row:10:Blondell Sosig:4013008122:3:D8:0B:9A:CC:88:BF
contact:row:11:Amber Altingle:8885554422:2:D8:0B:9A:CC:88:BF
contact:row:12:Frank Helgenson:8885554422:2:D8:0B:9A:CC:88:BF
contact:row:13:Hiro Xin:8885554422:2:D8:0B:9A:CC:88:BF
contact:row:14:Baley Balix:6316773675:2:D8:0B:9A:CC:88:BF
contact:row:15:Henry Halgor:6316773675:2:D8:0B:9A:CC:88:BF
contact:row:16:Hammy Xevronic:6316773675:2:D8:0B:9A:CC:88:BF
I've tried storing the very first contact and letting it read from the Cursor until it matches up with that contact, but since the "id" variable keeps increasing, it makes the contact different enough to be ignored. I removed the ID portion of the contact, changed the URI from the default to one with an explicit REMOVE_DUPLICATE_ENTRIES = 1 parameter on it, and I tried to bring in the "real" count using ContactsContract.Data._COUNT in order to check the number of entries on the cursor against it, but that just crashes with "no such column _COUNT".
Is there any reason why the cursor would be pulling duplicate contacts like this? Is there something wrong with the structure of my query that is causing this sort of duplication?
let's recap the way ContactsContract DB is organized:
Contacts table - contains one row per contact, but hardly any information
RawContacts table - can have multiple rows, each assigned to a single contact-ID (from the previous table), contains a logical group of multiple Data rows usually for a single SyncProvider such as Google.
Data table - contains the actual data of a RawContact, each row has a MIMETYPE column which states what kind of data this row is about (phone, email, name, etc.) + 15 data columns to hold the information itself.
There are also pseudo tables, such as ContactsContract.CommonDataKinds.Phone which you are querying in your code, which basically queries over the Data table but with a specific MIMETYPE value, for example Phone.CONTENT_ITEM_TYPE.
In your code you are querying over CommonDataKinds.Phone.CONTENT_URI which means you are asking for all the different phone numbers in the DB.
So if a single contact has 3 phone numbers, you will get 3 rows for that contact (each with a different phone number).
However looking at your output, it seems like every contact has a single phone number in the DB, but it looks like the contacts themselves are duplicated.
So for example Amber Altingle has contact ID 3 and also 11, which means you have two separate contacts named Amber Altingle.
This is not duplication in the query code, but possibly duplication in the contact creation code.

Edit Call history names

I've implemented a contacts app, and I would like my application's contact names to be displayed in the device's call log history (Phone app) in case I receive/make a call to these numbers. How could I achieve that?
The CallLog.Calls table contains fields for caching names, because these are cached names, they're not expected to always be true, and are refreshed from time to time.
Usually, in most Phone/Call-log apps, when you open the call-log it'll display the calls list along with their cached names stored in the Calls table, and then spin up a background service that refreshes cached names, adding names to numbers recently saved as contacts, or updating names that had recently changed.
So if your app stored some number from the call log as a contact, if you then launch the call log app you should see the updated name appearing within a second or two.
If you want to store that name programatically in your code, you can do that easily:
String someNumber = "+12125551234";
String aName = "Jane Addams";
int numberType = Phone.TYPE_MOBILE; // see https://developer.android.com/reference/android/provider/ContactsContract.CommonDataKinds.Phone#column-aliases
final ContentValues values = new ContentValues(2);
values.put(Calls.CACHED_NAME, aName);
values.put(Calls.CACHED_NUMBER_TYPE, numberType);
// on Lollipop+ device, you can also set Calls.CACHED_LOOKUP_URI and Calls.CACHED_FORMATTED_NUMBER
getContentResolver().update(Calls.CONTENT_URI, values, Calls.NUMBER + "='" + someNumber + "'", null);
Thank you #PedroHawk. I found the answer in the link you provided. More specifically, I will create an Account of my app in the Device Accounts and then use a SyncAdapter to sync the contact data from my web service to the ContactsProvider of the device.

Detect if an android contact has been deleted

I am trying to maintain a contact database and get a callback for Add/Update/Delete as soon as something changes in the URI.
I have written a ContentObserver to observe on ContactsContract.Contacts.CONTENT_URI on contacts. I get a callback as soon as a contact changes and then I update my database by checking ContactsContract.Contacts.CONTACT_LAST_UPDATED_TIMESTAMP.
While this works fine for add/update, it does does not work for deleting a contact.
I do not want to parse all the contacts that I have in memory and check against android database. That would take time and CPU.
I know there exists many question of these types but I am not able to figure out things specific to deleting the contact.
Does there exist a way to perform this ?
As I have posted in above comment as well, following code works for API level 18 and above.
You can query on a uri ContactsContract.DeletedContacts.CONTENT_URI to get the list of all the contacts that have been deleted.
My query looks like following :
String selection = ContactsContract.DeletedContacts.CONTACT_DELETED_TIMESTAMP + " > ?";
String[] selectionArgs = new String[]{String.valueOf(mLastContactDeleteTime)};
Cursor cursor = mContext.getContentResolver().query(ContactsContract.DeletedContacts.CONTENT_URI, null, selection, selectionArgs, null);

android how to tag phone number of a contact programmatically

i did a lot of research but couldn't find anything to help;
my problem is: i need to create an application where the user can select some of the contacts on his phone to be added to this application where he/she can later communicate with them via sms in a special template. but the user need to select only one phone number to be active to this user on this application. this choice must be caved for later logons.
i was able to retrieve contacts and their phone numbers using lookupkey (which will be saved in my application as a reference for preselected users), but i couldn't figure out how to tag the needed phone number, i was thinking of adding a flag to the phone number but i dont know how, i dont know if this is the right way to do it, i thought of setting the selected phone number as primary then query t when needed... or simply save the phone number id (but i am not sure if saving the id is safe in case user changed the phone numer)...
thx for any help...
After a long period of trial and error I found the solution to my problem. I will be using the contacts lookup key to store the contact and the phone id to store the phone number...as follows:
String selection = ContactsContract.CommonDataKinds.Phone.LOOKUP_KEY + " = '" + lookupkey+ "' and "+Phone._ID+"='"+phoneid+"'";
String[] projection =new String[] {Phone._ID, Phone.DISPLAY_NAME, Phone.NUMBER};
Cursor managedCursor = getContentResolver()
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
projection, selection, null, Phone.DISPLAY_NAME + " ASC");
I'm a bit new to all this stuff. As I understand it, an id match is fast, but may not be stable. If a key+id match fails, you should also try a slower match using only the key - Jeffrey Scofield's SQL selection string could be changed to try id-and-key OR key-only (trusting the query optimiser to prioritize the id match).
I haven't had much luck finding information concerning the wisdom of storing the key long term.

Trying to replicate android homescreen Contact shortcuts, with issues

Okay, I'm trying to replicate the shortcuts which get placed on the homescreen when creating a contact shortcut, example shown:
I've got a working QuickContactBadge, which when clicked shows the QuickContact toolbar. However, I have two things I'm having trouble with.
One is the picture. I tried using the code from this question (I altered it by adding a parameter to pass in the contact ID). I then assign the image to my QuickContactBadge as so:
bdg.setImageURI(getPhotoUri(cid));
It definitely gets pictures, but it is getting TOTALLY the wrong picture. As illustrated here:
As you can see, the image it returned for Domino's is clearly NOT the Domino's logo.
I'm getting my contact ID to pass to the function from this code:
public static String[] ContactsProjection = new String[] {
Contacts._ID,
Contacts.LOOKUP_KEY,
Contacts.DISPLAY_NAME
};
public static Cursor getContacts() {
ContentResolver cr = CoreLib.ContentResolver();
Cursor contacts = cr.query(
ContactsContract.Data.CONTENT_URI,
ContactsProjection,
null, null,
Contacts.TIMES_CONTACTED + " DESC"
);
return contacts;
}
Which I believe should be returning me the proper ID for each record. Yes?
Next how do I get exactly the thumbnail shrunk or cropped as the shortcut shows it?
I was a little disappointed to see that the QuickContactBadge doesn't actually replicate the whole look and feel of the QuickContact shortcut, ... but just acts as in invocation target for the QuickContact card. Is there any built in way to easily replicate the contact shortcut in it's entirety, invocation, image, text and all, without needing to reproduce the whole thing from scratch?
Ah HAH! Figured out how to get the correct photo. While this seems counter-intuitive, when building your field projection to query the contacts, the fields Contacts._ID and ContactsContract.Data.CONTACT_ID are not the same thing.
ContactsContract.Data.CONTACT_ID is the correct one to pass in to get the photo. Use this, and everything is now golden.

Categories

Resources