Retrieve contacts from Android Froyo 2.2 - android

im using the following code segment to fetch contact names and numbers, it works fine on the emulator, but when i install the app in my Froyo 2.2.1, it just returns me the name, and instead of returning me the number it returns, 'null', can anyone help me solve this issue ?
will greatly appreciate any solution. Thanks
ContentResolver r = getContentResolver();
Cursor cursor = r.query(People.CONTENT_URI, null, null, null, null);
// Let activity manage the cursor
// startManagingCursor(cursor);
// Log.d(TAG, "cursor.getCount()=" + cursor.getCount());
// Get value from content provider
int nameIndex = cursor.getColumnIndex(People.NAME);
int numberIndex = cursor.getColumnIndex(People.NUMBER);//OrThrow(People.NUMBER);
cursor.moveToFirst();
StringBuilder s = new StringBuilder();
do {
String name = cursor.getString(nameIndex);
String number = cursor.getString(numberIndex);
s.append(name+ ": " + number + "\n");
} while (cursor.moveToNext());

The People API is deprecated try using the ContactsContract API which was already introduced for android 2.0+.
You can look at this blog post about using the contactscontract or the api documentation

Related

SMS numbers are incorrect?

I am using this code to retrieve the SMS from Emulator.After that I need to Post it in to the DropBox.I saved some messages to Emulator, it retrieves two things Number and Body.At the time of retrieval it displays the
Wrong Numbers but correct Body. How to correct the number, I save the numbers in to a variable Number. My code is here, I am using 2.1 version.
code
ContentResolver cr = getContentResolver();
Cursor c = getContentResolver().query(Uri.parse("content://sms/inbox"), null, null, null, null);
while(c.moveToNext()){
Number = c.getInt(c.getColumnIndexOrThrow("address"));
Body = c.getString(c.getColumnIndexOrThrow("body")).toString();
smslist.add( Number + ":" +"\n"+ Body);
}
itemAdapter.notifyDataSetChanged();
c.close();
Any solution ?
In your code you are using
Number = c.getInt(c.getColumnIndexOrThrow("address"));
use c.getString(c.getColumnIndexOrThrow("address")) Method instead of getInt() method
see below link too, The type column in SMS uri
retrieving number.
Treat the address as String instead of a Int.
I think it should resolve the issue.
String str = cursor.getString( c.getColumnIndexOrThrow("address"));
regards,
dattatray.

Android java.lang.IllegalArgumentException: Invalid column _count error while retrieving contacts

I am working on a project where I need to list down all the contacts. I am following this article.
My AndroidManifest.xml contains below, so i can read the contacts:
<uses-permission android:name="android.permission.READ_CONTACTS"/>
Code is here:
private void getContacts() {
try {
// Form an array specifying which columns to return.
String[] projection = new String[] {
People._ID,
People._COUNT,
People.NAME,
People.NUMBER};
// Get the base URI for the People table in the Contacts content provider.
Uri contacts = People.CONTENT_URI;
// Make the query.
Cursor managedCursor = managedQuery(contacts,
projection, // Which columns to return
null, // Which rows to return (all rows)
null, // Selection arguments (none)
// Put the results in ascending order by name
People.NAME + " ASC");
printContacts(managedCursor);
}
catch(Exception ex) {
Log.d("Contacts",ex.toString());
}
}
private void printContacts(Cursor cur){
if (cur.moveToFirst()) {
String name;
String phoneNumber;
int nameColumn = cur.getColumnIndex(People.NAME);
int phoneColumn = cur.getColumnIndex(People.NUMBER);
String imagePath;
do {
// Get the field values
name = cur.getString(nameColumn);
phoneNumber = cur.getString(phoneColumn);
Log.d("Contacts","Name: "+ name + " **** Phone: "+ phoneNumber);
} while (cur.moveToNext());
}
}
When I run it on the Emulator(2.3.3) it throws below error:
java.lang.IllegalArgumentException: Invalid column _count
Can someone fix it?
Great thanks for your valuable time & help.
If you remove the string People._COUNT everything works
See also: Android SDK - List All Users
Android People class is deprecated. You should use ContactsContract instead.
Since you run it on Emulator API level 10, and the class is deprecated since API level 5, there's no reason to keep using People.

How to get contact name details for a particular contact

I want the Name of the Contact which includes (FAMILY_NAME, GIVEN_NAME,MIDDLE_NAME,PHONETIC_FAMILY_NAME,PHONETIC_GIVEN_NAME,PHONETIC_MIDDLE_NAME,PREFIX,SUFFIX).
I know that column names of the above data that starts with
android.provider.ContactsContract.CommonDataKinds.StructuredName
But i am unable to get the URI of the data.
I was working on device with api level 8 so i want to fetch these details using
android.provider.ContactsContract
I have searched about this in commumnity but i can't get the desired result.
I am working for 4 hours on this.
Any help will be appreciated.
I was using this code
Cursor cursor = activity.managedQuery(android.provider.ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if (cursor != null)
{
if (cursor.moveToFirst())
{
int rows = cursor.getCount();
int cols = cursor.getColumnCount();
do
{
int _id = cursor.getInt(cursor.getColumnIndex("_id"));
int times_contacted = cursor.getInt(cursor.getColumnIndex("times_contacted"));
int has_phone_number = cursor.getInt(cursor.getColumnIndex("has_phone_number"));
int send_to_voicemail = cursor.getInt(cursor.getColumnIndex("send_to_voicemail"));
int starred = cursor.getInt(cursor.getColumnIndex("starred"));
// Here i want the contact names But i dont know what column name i have to pass to get them
}
while (cursor.moveToNext());
}
cursor.close();
}
Thanks in advance.
Ok, Try this, and let me know what happen,
Look at ContactsContract.CommonDataKinds.StructuredName class. You can find there all columns you are looking for.
String whereName = ContactsContract.Data.MIMETYPE + " = ?";
String[] whereNameParams = new String[] { ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE };
Cursor nameCur = contentResolver.query(ContactsContract.Data.CONTENT_URI, null, whereName, whereNameParams, ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME);
while (nameCur.moveToNext()) {
String given = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME));
String family = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME));
String display = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME));
}
nameCur.close();
Look at this SO question How to get the firstname and lastname from android contacts?
EDIT: Look at this complete example for working with android contacts Working With Android Contacts, Now if you want to get more info from any contacts then add a particular column on that cursor. For more columns look at ContactsContract.CommonDataKinds.

Cannot find Facebook contacts in RawContacts

I'm trying to build a contacts-managing application. On my phone I have contacts from a couple of accounts including Facebook and HTC Facebook. For some reason I cannot retrieve these contacts from the RawContacts table of ContactsContract:
managedQuery(ContactsContract.RawContacts.CONTENT_URI, new String[] {
ContactsContract.RawContacts._ID,
ContactsContract.RawContacts.CONTACT_ID,
ContactsContract.RawContacts.ACCOUNT_NAME,
ContactsContract.RawContacts.ACCOUNT_TYPE,
}, ContactsContract.RawContacts.ACCOUNT_TYPE + " = 'com.facebook.auth.login'", null, null)
This query returns no results. If I repace the account type with com.htc.socialnetwork.facebook, I still get no results. There are many Facebook contacts on my phone; how to retrieve them?
I think I found the answer here: How to get a contact's facebook id or url from native contacts / content resolver?
Seems that access to Facebook contacts is restricted.
Yes, the Facebook contacts are secured, but can be hijacked with a little sneaky SQLite Injection. NO- I am not going to post here on this page, but is there any reason you do not just use Facebook authentication and get the contacts THAT way? The Facebook contacts don't really have anything useful in them anyway, and it is just more secure and more likely to work ALL the
There is definitely no way to do this in a standard way. So, we must use an SQLi injection (as roger commented) in order to be able to hack the contacts database and get the Facebook avatars. The following code works on most Motorolas, which use Motoblur, on Android 2.2 or higher:
public static Bitmap loadFacebookAvatar(Context context, long personId) {
String[] rawProjection = {ContactsContract.RawContacts._ID};
String contactIdAssertion = ContactsContract.RawContacts.CONTACT_ID + " = " + personId;
String rawWhere = new StringBuilder()
.append(contactIdAssertion).append(") UNION ALL SELECT ")
.append(ContactsContract.RawContacts._ID).append(" FROM view_raw_contacts WHERE (")
.append(contactIdAssertion).toString();
Cursor query = context.getContentResolver().query(ContactsContract.RawContacts.CONTENT_URI,
rawProjection,
rawWhere, null, null);
if (query != null && query.moveToFirst()) {
do {
long id = query.getLong(query.getColumnIndex(ContactsContract.RawContacts._ID));
String[] projection = {ContactsContract.CommonDataKinds.Photo.PHOTO};
Uri uri = ContactsContract.Data.CONTENT_URI;
String mimeTypeAssertion = ContactsContract.Data.MIMETYPE + "='" + ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE + "'";
String photoAssertion = ContactsContract.CommonDataKinds.Photo.PHOTO + " IS NOT NULL";
String rawContactIdAssertion = ContactsContract.CommonDataKinds.Photo.RAW_CONTACT_ID + " = " + id;
String where = new StringBuilder().append(mimeTypeAssertion).append(" AND ")
.append(photoAssertion).append(" AND ").append(rawContactIdAssertion)
.append(") UNION ALL SELECT ").append(ContactsContract.CommonDataKinds.Photo.PHOTO)
.append(" FROM view_data WHERE (").append(photoAssertion).append(" AND ")
.append(rawContactIdAssertion).toString();
Cursor photoQuery = context.getContentResolver().query(uri, projection, where, null, null);
if (photoQuery != null && photoQuery.moveToFirst()) {
do {
byte[] photoData = photoQuery.getBlob(photoQuery.getColumnIndex(ContactsContract.CommonDataKinds.Photo.PHOTO));
if (photoData != null) {
return BitmapFactory.decodeByteArray(photoData, 0, photoData.length, null);
}
} while (photoQuery.moveToNext());
}
} while (query.moveToNext());
}
return null;
}
For other handsets you must get the contacts database and analyze it in order to determine how to apply the SQL Injection, which requires a rooted phone.

How to look-up a contact's name from their phone number on Android?

I am trying to get the sender's name from the contacts database using a content provider.
The problem is I don't know how to implement it. Like now I can only pull the phone number from the smsMessage. I need to check to see if the phone number that is calling is in the users contacts first and if it is display the name if it is not then display the number.
Yes, this is possible using ContactsContract.PhoneLookup.CONTENT_FILTER_URI in Android 2.0 and higher and Contacts.Phones.CONTENT_FILTER_URL in Android 1.6 and earlier.
For example usage, see the documentation for ContactsContract.PhoneLookup. Excerpt below:
// Android 1.6 and earlier (backwards compatible for Android 2.0+)
Uri uri = Uri.withAppendedPath(Contacts.Phones.CONTENT_FILTER_URL, Uri.encode(phoneNumber));
// Android 2.0 and later
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
// Query the filter URI
String[] projection = new String[]{ PhoneLookup.DISPLAY_NAME, ...
Cursor cursor = context.getContentResolver().query(uri, projection, ...
UPDATE: The format of the phone number does not matter. Comparison is robust and highly optimized on Android; it's done using a native sqlite function named PHONE_NUMBERS_EQUAL. For more details, search the codebase for this method. By the way, I'm not certain if it's safe to use that function directly in your own apps, but I wouldn't.
Here's what I did
ContentResolver localContentResolver = this.mContext.getContentResolver();
Cursor contactLookupCursor =
localContentResolver.query(
Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(phoneNumber)),
new String[] {PhoneLookup.DISPLAY_NAME, PhoneLookup._ID},
null,
null,
null);
try {
while(contactLookupCursor.moveToNext()){
String contactName = contactLookupCursor.getString(contactLookupCursor.getColumnIndexOrThrow(PhoneLookup.DISPLAY_NAME));
String contactId = contactLookupCursor.getString(contactLookupCursor.getColumnIndexOrThrow(PhoneLookup._ID));
Log.d(LOGTAG, "contactMatch name: " + contactName);
Log.d(LOGTAG, "contactMatch id: " + contactId);
}
} finally {
contactLookupCursor.close();
}
Passing in your phone number you already have into Uri.encode(phoneNumber)

Categories

Resources