我在Contacts
表中进行迭代,每次迭代都在Phone
表上进行迭代,所以它需要appx。 4秒为243个联系人做联系人列表(没有迭代它立即加载的电话号码)。我确信有办法让它更快。
已经进行了预测,只能获取所需的列,但还没有那么多改进。也许我应该改进SQLite查询或以其他方式迭代:
Contact realmContact = new Contact();
Uri uri = Contacts.CONTENT_URI;
String[] projection = {
Contacts.LOOKUP_KEY,
Contacts.DISPLAY_NAME_PRIMARY,
Contacts.LAST_TIME_CONTACTED,
Contacts.HAS_PHONE_NUMBER
};
String selection = "((" + CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY + " NOTNULL) AND ("
+ Contacts.HAS_PHONE_NUMBER + "=1) AND ("
+ CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY + " != '' ))";
Cursor phones = getActivity()
.getContentResolver()
.query(uri, projection, selection, null, null);
while (phones.moveToNext()) {
String id = phones.getString(phones.getColumnIndex(Contacts.LOOKUP_KEY));
String name = phones.getString(phones.getColumnIndex(Contacts.DISPLAY_NAME_PRIMARY));
String lastTimeContacted = phones.getString(phones.getColumnIndex(Contacts.LAST_TIME_CONTACTED));
long data = Long.parseLong(lastTimeContacted);
String date = new SimpleDateFormat("dd/MM/yyyy | HH:mm").format(new Date(data));
if (Integer.parseInt(phones.getString(phones.getColumnIndex(Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = getActivity().getContentResolver().query(
CommonDataKinds.Phone.CONTENT_URI,
new String[]{CommonDataKinds.Phone.NUMBER},
CommonDataKinds.Phone.LOOKUP_KEY + " = ?",
new String[]{id}, null);
int iterationCounter = 0;
String phoneNumber = "";
while (pCur.moveToNext()) {
phoneNumber += iterationCounter == 0 ?
pCur.getString(pCur.getColumnIndex(CommonDataKinds.Phone.NUMBER))
: "," + pCur.getString(pCur.getColumnIndex(CommonDataKinds.Phone.NUMBER));
iterationCounter += 1;
}
realmContact.setNumber(phoneNumber);
Log.i("asd-number", phoneNumber);
pCur.close();
}
realmContact.setId(id);
realmContact.setName(name);
realmContact.setLastTimeContacted(
getActivity().getResources()
.getString(R.string.contacts_list_fragment_last_call)
+ date);
realmContact.setIsBeingSaved(true);
_realm.insertOrUpdate(realmContact);
答案 0 :(得分:0)
正如评论中提到的@pskink,您需要查询Phone
表。
要通过联系人获取手机列表,您可以保留HashMap
从contactId
到List
手机。
这里有一个可能有用的小片段(你可能想稍微调整一下这个集合,每个联系人只能存储一次显示名称):
HashMap<Long, ArrayList<String>> phones = new HashMap<Long, ArrayList<String>>();
String[] projection = new String[] { Phone.CONTACT_ID, Phone.DISPLAY_NAME, Phone.NUMBER };
Cursor c = cr.query(Phone.CONTENT_URI, projection, null, null, null);
while (c != null && c.moveToNext()) {
long contactId = c.getLong(0);
ArrayList<String> list = phones.get(contactId);
if (list == null) {
ArrayList<String> list = new ArrayList<String>();
phones.put(contactId, list);
}
list.add(c.getString(1) + " " + c.getString(2));
}