Get contact & insert contact trên Android 1.6 18/05/2011
Posted by banghn in Android Development.Tags: android, android 1.6, blog it&life, bloghnb, cap nhat danh ba, getcontactlist, insert contact list, lay danh ba
trackback
Hii các bạn,… Lâu quá không post bài.
Hôm nay làm android đụng tới cái vấn đề lấy danh sách tên, số điện thoại, email,…. trên ở danh bạ lên. (Get contact list)
Với những phiên bản android sdk 2.0 trở về sau thì việc lấy danh bạ không có mấy khó khăn, các bạn có thể search trên các trang tìm kiếm và cho bạn khá nhiều kết quả. Nhưng với 1.6 thì hơi khó tìm một tí, nhưng cũng tìm và suy ra từ các phiên bản sdk về sau. Mình post lại cho các bạn tham khảo luôn… (Hôm nào rảnh rổi thì mình tổng hợp tất cả cho các phiên bản sau này luôn)
Đầu tiên để có thể lấy danh bạ từ điện thoại thì trong project của bạn phải khai báo quyền truy cập lấy và cập nhật contact trong AndroidManifest.xml
Code khai báo như thế này:
<uses-permission android:name=”android.permission.READ_CONTACTS” />
<uses-permission android:name=”android.permission.WRITE_CONTACTS” />
Rồi, bạn có thể vào activity của bạn để bắt đầu lấy danh bạ từ phone như sau:
final Cursor c = managedQuery(Contacts.People.CONTENT_URI, null, null,
null, null);
String[] from = new String[] { People.NAME };
if (c.getCount() > 0) {
while (c.moveToNext()) {
//lay ten trong danh ba
String username = c.getString(c
.getColumnIndex(Contacts.People.NAME));
if(username!=null)
Log.i(“Contact name “, username);
//lay so phone
String phone = c.getString(c
.getColumnIndex(Contacts.People.NUMBER));
if(phone != null)
Log.i(“Contact name “, phone);
}
}
Việc cập nhật contact xuống phone được thực hiện như sau:
ContentValues personValues = new ContentValues();
// dinh nghia mot contact user moi
personValues.put(Contacts.People.NAME, n);
personValues.put(Contacts.People.STARRED, 1);
Uri newPersonUri = Contacts.People
.createPersonInMyContactsGroup(getContentResolver(), personValues);
if (newPersonUri != null) {
//phone number
ContentValues mobileValues = new ContentValues();
Uri mobileUri = Uri.withAppendedPath(newPersonUri, Contacts.People.Phones.CONTENT_DIRECTORY);
mobileValues.put(Contacts.Phones.NUMBER,p);
mobileValues.put(Contacts.Phones.TYPE, Contacts.Phones.TYPE_MOBILE);
//cap nhat contact
Uri phoneUpdate = getContentResolver()
.insert(mobileUri, mobileValues);
if (phoneUpdate == null) {
try {
throw new Exception(
“Failed to insert mobile phone number”);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
else
{
Log.i(“Contact name “, “NULLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLl”);
}
Comments»
No comments yet — be the first.