有什么办法缩短这个时间呢? 我用光标运行和开出的姓名,电话号码和电子邮件
如果我从它在3秒内结束查询循环中删除电话号码查询
任何想法我怎么能提高该查询?
也许我做错了什么在我的查询?
(显然我做的异步但仍...这是一个很长的时间,用户不能等待)
希望有人能分享此他的想法
这是我的code
ContentResolver的CR = getContentResolver();
光标CUR = cr.query(ContactsContract.Contacts.CONTENT_URI,
NULL,NULL,NULL,NULL);
如果(cur.getCount()大于0){
而(cur.moveToNext()){
AddressBookEntity ADR =新AddressBookEntity();
字符串ID = cur.getString(CUR
.getColumnIndex(ContactsContract.Contacts._ID));
字符串名称= CUR
.getString(CUR
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
adr.fullName =名称;
光标emailCur = CR
.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
空值,
ContactsContract.CommonDataKinds.Email.CONTACT_ID
+=?,新的String [] {ID},
空值);
而(emailCur.moveToNext()){
//这将让你获得多个电子邮件地址
//如果电子邮件地址被存储在一个阵列
字符串email = emailCur
.getString(emailCur
.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
如果(!Utils.IsNullOrEmptyString(电子邮件)){
adr.email =电子邮件;
}
}
emailCur.close();
如果(整数
.parseInt(cur.getString(CUR
.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)))> 0){
光标pCur = CR
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
空值,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+=?,
新的String [] {ID},NULL);
INT phoneIndex = 0;
而(pCur.moveToNext()){
串号= pCur.getString(pCur
.getColumnIndex(Phone.NUMBER));
字符串全国= Utils.GetCountryFromNumber(
数,应用程序);
数= Utils.GetFullPhoneNumber(号,应用程序);
如果(phoneIndex == 0){
如果(!Utils.IsNullOrEmptyString(编号)){
adr.contactAdressBookId = ID;
adr.phoneNumber =号;
adr.userInsertedId = app.userCred.userId;
adr.country =国家;
myContacts.add(ADR);
}
} 其他 {
如果(!Utils.IsNullOrEmptyString(编号)){
AddressBookEntity adrMore =新AddressBookEntity();
adrMore.fullName = adrMore.fullName;
adrMore.country = adrMore.country;
adrMore.email = adrMore.email;
adrMore.phoneNumber =号;
adrMore.contactAdressBookId = ID;
adrMore.country =国家;
myContacts.add(adrMore);
}
}
}
pCur.close();
}
}
cur.close();
解决方案
与下面的code 59的接触我上了仿真结果如下:
D╔══════查询执行统计═══════
ð║得到59接触
ð║查询了0.012秒(12毫秒)
ð ╚════════════════════════════════════
好了,这是最好的时机,但平均为25〜35毫秒(59接点),在一些回调的onClick添加以下code和运行多次才能获得的平均时间,在你的情况,你应该得到30 *五十九分之七百=〜 300-400 毫秒,而不是3秒,更何况小;)
它使用开放的设置为 Contactables.CONTENT_URI 添加API级别18,但你可以使用 ContactsContract.Data.CONTENT_URI 建筑为pre 18 API设备时
名单,其中,AddressBookContact>名单=新的LinkedList< AddressBookContact>();
LongSparseArray< AddressBookContact>阵列=新LongSparseArray< AddressBookContact>();
长时间启动= System.currentTimeMillis的();
的String []投影= {
ContactsContract.Data.MIMETYPE,
ContactsContract.Data.CONTACT_ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Contactables.DATA,
ContactsContract.CommonDataKinds.Contactables.TYPE,
};
串选择= ContactsContract.Data.MIMETYPE +在(?,?);
的String [] selectionArgs两个= {
ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE,
ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,
};
字符串排序顺序= ContactsContract.Contacts.SORT_KEY_ALTERNATIVE;
开放的我们的uri = ContactsContract.CommonDataKinds.Contactables.CONTENT_URI;
//我们也可以使用开放的URI = ContactsContract.Data.CONTENT_URI;
// OK,下面就让我们一...
光标光标= getContentResolver()查询(URI,投影,选择,selectionArgs两个,排序顺序)。
最终诠释mimeTypeIdx = cursor.getColumnIndex(ContactsContract.Data.MIMETYPE);
最终诠释idIdx = cursor.getColumnIndex(ContactsContract.Data.CONTACT_ID);
最终诠释nameIdx = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
最终诠释dataIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Contactables.DATA);
最终诠释typeIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Contactables.TYPE);
而(cursor.moveToNext()){
长ID = cursor.getLong(idIdx);
AddressBookContact addressBookContact = array.get(ID);
如果(addressBookContact == NULL){
addressBookContact =新AddressBookContact(ID,cursor.getString(nameIdx),getResources());
array.put(ID,addressBookContact);
list.add(addressBookContact);
}
整型= cursor.getInt(typeIdx);
字符串数据= cursor.getString(dataIdx);
字符串MIMETYPE = cursor.getString(mimeTypeIdx);
如果(mimeType.equals(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)){
// MIMETYPE == ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE
addressBookContact.addEmail(类型,数据);
} 其他 {
// MIMETYPE == ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE
addressBookContact.addPhone(类型,数据);
}
}
长毫秒= System.currentTimeMillis的() - 启动;
cursor.close();
//完成!显示结果...
INT I = 1;
对于(AddressBookContact addressBookContact:名单){
Log.d(TAG,AddressBookContact#+ I + +:+ addressBookContact.toString(真));
}
最后弦乐CON =< B><字体颜色=#FF9900>中;
最后弦乐COFF =&其中; /字体>&所述; / B>中;
跨区L1 = Html.fromHtml(有+ CON + array.size()+ COFF +的接触与LT; BR />中);
跨区L2 = Html.fromHtml(查询用+ CON + MS / 1000F + COFF +S(+ CON + MS + COFF +毫秒));
Log.d(TAG,ñn╔══════查询执行统计═══════);
Log.d(TAG,║+ L1);
Log.d(TAG,║+ 12);
Log.d(TAG, "╚════════════════════════════════════" );
SpannableStringBuilder味精=新SpannableStringBuilder()追加(L1).append(12)。
的LinearLayout LL =新的LinearLayout(本);
ll.setOrientation(LinearLayout.VERTICAL);
TextView的电视=新的TextView(本);
tv.setTextSize(20);
tv.setBackgroundColor(0xff000033);
tv.setPadding(24,8,24,24);
tv.setText(MSG);
ll.addView(电视);
ListView的LV =新的ListView(本);
lv.setAdapter(新ArrayAdapter< AddressBookContact>(这一点,android.R.layout.simple_list_item_1,列表));
ll.addView(LV);
新AlertDialog.Builder(本).setView(LL).setPositiveButton(关闭,NULL).create()显示()。
辅助 AddressBookContact
类:
类AddressBookContact {
专用长ID;
私人资源资源;
私人字符串名称;
私人LongSparseArray<字符串>电子邮件;
私人LongSparseArray<字符串>手机;
AddressBookContact(长ID,字符串名称,资源RES){
this.id = ID;
this.name =名称;
this.res =资源;
}
@覆盖
公共字符串的toString(){
返回的toString(假);
}
公共字符串的toString(布尔富){
SpannableStringBuilder建设者=新SpannableStringBuilder();
如果(富){
builder.append(ID).append(Long.toString(ID))
.append(名).append( u001b [1分)追加(姓名).append( u001b [0米)。
} 其他 {
builder.append(名称);
}
如果(手机!= NULL){
builder.append(ñ tphones:);
的for(int i = 0; I< phones.size();我++){
整型=(INT)phones.keyAt(我);
builder.append(ContactsContract.CommonDataKinds.Phone.getTypeLabel(RES,类型,))
。附加(: )
.append(phones.valueAt(ⅰ));
如果第(i + 1&其中; phones.size()){
builder.append(,);
}
}
}
如果(电子邮件!= NULL){
builder.append(ñ temails:);
的for(int i = 0; I< emails.size();我++){
整型=(INT)emails.keyAt(我);
builder.append(ContactsContract.CommonDataKinds.Email.getTypeLabel(RES,类型,))
。附加(: )
.append(emails.valueAt(ⅰ));
如果第(i + 1&其中; emails.size()){
builder.append(,);
}
}
}
返回builder.toString();
}
公共无效addEmail(整型,字符串地址){
如果(电子邮件== NULL){
电子邮件=新LongSparseArray<字符串>();
}
emails.put(类型,地址);
}
公共无效addPhone(int型的,串号){
如果(电话== NULL){
手机=新LongSparseArray<字符串>();
}
phones.put(类型,数量);
}
}
Is there any way to shorten this time? I'm running with the cursor and takes the name, phone numbers and emails
if I remove the phone numbers query from the query loop it ends in 3 seconds
any idea how can I improve that query?
Maybe I'm doing something wrong in my query?
(Obviously I'm doing it async but still... it's a very long time that a user can't wait)
Hope someone can share his thoughts about this
this is my code
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
AddressBookEntity adr = new AddressBookEntity();
String id = cur.getString(cur
.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur
.getString(cur
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
adr.fullName = name;
Cursor emailCur = cr
.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID
+ " = ?", new String[] { id },
null);
while (emailCur.moveToNext()) {
// This would allow you get several email addresses
// if the email addresses were stored in an array
String email = emailCur
.getString(emailCur
.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
if (!Utils.IsNullOrEmptyString(email)) {
adr.email = email;
}
}
emailCur.close();
if (Integer
.parseInt(cur.getString(cur
.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?",
new String[] { id }, null);
int phoneIndex = 0;
while (pCur.moveToNext()) {
String number = pCur.getString(pCur
.getColumnIndex(Phone.NUMBER));
String country = Utils.GetCountryFromNumber(
number, app);
number = Utils.GetFullPhoneNumber(number, app);
if (phoneIndex == 0) {
if (!Utils.IsNullOrEmptyString(number)) {
adr.contactAdressBookId = id;
adr.phoneNumber = number;
adr.userInsertedId = app.userCred.userId;
adr.country = country;
myContacts.add(adr);
}
} else {
if (!Utils.IsNullOrEmptyString(number)) {
AddressBookEntity adrMore = new AddressBookEntity();
adrMore.fullName = adrMore.fullName;
adrMore.country = adrMore.country;
adrMore.email = adrMore.email;
adrMore.phoneNumber = number;
adrMore.contactAdressBookId = id;
adrMore.country = country;
myContacts.add(adrMore);
}
}
}
pCur.close();
}
}
cur.close();
解决方案
with the following code for 59 contacts i got the following results on the emulator:
D ╔══════ query execution stats ═══════
D ║ got 59 contacts
D ║ query took 0.012 s (12 ms)
D ╚════════════════════════════════════
ok, that was the best time, but the average is 25-35 ms (for 59 contacts), add the following code in some onClick callback and run in several times in order to get the average time, in your case you should get 30 * 700 / 59 = ~300-400 ms, not 3 seconds, let alone one minute ;)
it uses Uri set to Contactables.CONTENT_URI added in API level 18 but you can use ContactsContract.Data.CONTENT_URI when building for pre 18 API devices
List<AddressBookContact> list = new LinkedList<AddressBookContact>();
LongSparseArray<AddressBookContact> array = new LongSparseArray<AddressBookContact>();
long start = System.currentTimeMillis();
String[] projection = {
ContactsContract.Data.MIMETYPE,
ContactsContract.Data.CONTACT_ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Contactables.DATA,
ContactsContract.CommonDataKinds.Contactables.TYPE,
};
String selection = ContactsContract.Data.MIMETYPE + " in (?, ?)";
String[] selectionArgs = {
ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE,
ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,
};
String sortOrder = ContactsContract.Contacts.SORT_KEY_ALTERNATIVE;
Uri uri = ContactsContract.CommonDataKinds.Contactables.CONTENT_URI;
// we could also use Uri uri = ContactsContract.Data.CONTENT_URI;
// ok, let's work...
Cursor cursor = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
final int mimeTypeIdx = cursor.getColumnIndex(ContactsContract.Data.MIMETYPE);
final int idIdx = cursor.getColumnIndex(ContactsContract.Data.CONTACT_ID);
final int nameIdx = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
final int dataIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Contactables.DATA);
final int typeIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Contactables.TYPE);
while (cursor.moveToNext()) {
long id = cursor.getLong(idIdx);
AddressBookContact addressBookContact = array.get(id);
if (addressBookContact == null) {
addressBookContact = new AddressBookContact(id, cursor.getString(nameIdx), getResources());
array.put(id, addressBookContact);
list.add(addressBookContact);
}
int type = cursor.getInt(typeIdx);
String data = cursor.getString(dataIdx);
String mimeType = cursor.getString(mimeTypeIdx);
if (mimeType.equals(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)) {
// mimeType == ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE
addressBookContact.addEmail(type, data);
} else {
// mimeType == ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE
addressBookContact.addPhone(type, data);
}
}
long ms = System.currentTimeMillis() - start;
cursor.close();
// done!!! show the results...
int i = 1;
for (AddressBookContact addressBookContact : list) {
Log.d(TAG, "AddressBookContact #" + i++ + ": " + addressBookContact.toString(true));
}
final String cOn = "<b><font color='#ff9900'>";
final String cOff = "</font></b>";
Spanned l1 = Html.fromHtml("got " + cOn + array.size() + cOff + " contacts<br/>");
Spanned l2 = Html.fromHtml("query took " + cOn + ms / 1000f + cOff + " s (" + cOn + ms + cOff + " ms)");
Log.d(TAG, "nn╔══════ query execution stats ═══════" );
Log.d(TAG, "║ " + l1);
Log.d(TAG, "║ " + l2);
Log.d(TAG, "╚════════════════════════════════════" );
SpannableStringBuilder msg = new SpannableStringBuilder().append(l1).append(l2);
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
TextView tv = new TextView(this);
tv.setTextSize(20);
tv.setBackgroundColor(0xff000033);
tv.setPadding(24, 8, 24, 24);
tv.setText(msg);
ll.addView(tv);
ListView lv = new ListView(this);
lv.setAdapter(new ArrayAdapter<AddressBookContact>(this, android.R.layout.simple_list_item_1, list));
ll.addView(lv);
new AlertDialog.Builder(this).setView(ll).setPositiveButton("close", null).create().show();
the helper AddressBookContact
class:
class AddressBookContact {
private long id;
private Resources res;
private String name;
private LongSparseArray<String> emails;
private LongSparseArray<String> phones;
AddressBookContact(long id, String name, Resources res) {
this.id = id;
this.name = name;
this.res = res;
}
@Override
public String toString() {
return toString(false);
}
public String toString(boolean rich) {
SpannableStringBuilder builder = new SpannableStringBuilder();
if (rich) {
builder.append("id: ").append(Long.toString(id))
.append(", name: ").append("u001b[1m").append(name).append("u001b[0m");
} else {
builder.append(name);
}
if (phones != null) {
builder.append("ntphones: ");
for (int i = 0; i < phones.size(); i++) {
int type = (int) phones.keyAt(i);
builder.append(ContactsContract.CommonDataKinds.Phone.getTypeLabel(res, type, ""))
.append(": ")
.append(phones.valueAt(i));
if (i + 1 < phones.size()) {
builder.append(", ");
}
}
}
if (emails != null) {
builder.append("ntemails: ");
for (int i = 0; i < emails.size(); i++) {
int type = (int) emails.keyAt(i);
builder.append(ContactsContract.CommonDataKinds.Email.getTypeLabel(res, type, ""))
.append(": ")
.append(emails.valueAt(i));
if (i + 1 < emails.size()) {
builder.append(", ");
}
}
}
return builder.toString();
}
public void addEmail(int type, String address) {
if (emails == null) {
emails = new LongSparseArray<String>();
}
emails.put(type, address);
}
public void addPhone(int type, String number) {
if (phones == null) {
phones = new LongSparseArray<String>();
}
phones.put(type, number);
}
}
相关推荐
最新文章