I am making a Android application which uses Contacts. The good thing is I managed somehow to make it work with Contacts.Phones as seen on many tutorials. The problem is that Contacts.Phones is deprecated and is replaced by ContactsContract. My application needs to work starting from Android 1.5+.
I need to do some simple operations like: - query all contacts - query for a specific contact - backup all contacts
What is the best way to achieve this, considering I need to have the application working on all versions of android. Do I need to check for current api level on the phone and have 2 code bl开发者_如何学Goocks, one before api 5 one after ?
Here is an optional solution
int apiVersion = android.os.Build.VERSION.SDK_INT;
if(apiVersion < 5) {
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(People.CONTENT_URI,
null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(People._ID));
String name = cur.getString(cur.getColumnIndex(People.DISPLAY_NAME));
}
}
} else {
String columns[] = new String[]{ ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME };
Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,
columns,
null,
null,
ContactsContract.Data.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
long id = Long.parseLong(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID)));
String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)).trim();
}
}
}
And here an tutorial to make application Supporting the old and new APIs in the same application this must help you.
Using ContentResolver
. Try this code:
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(
cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(
cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
//Query phone here. Covered next
}
}
}
精彩评论