您好我正在开发一个Android短信应用程序。我有一个活动,它将联系人加载到mPeopleList ArrayList中,如下面的代码,在doInBackground中调用
public void PopulatePeopleList()
{
mPeopleList.clear();
Cursor people = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if(people.getCount() == 0)
{
//No contacts found
}
while (people.moveToNext())
{
String contactName = people.getString(people.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String contactId = people.getString(people.getColumnIndex(ContactsContract.Contacts._ID));
String hasPhone = people.getString(people.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if ((Integer.parseInt(hasPhone) > 0))
{
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId,null, null);
while (phones.moveToNext())
{
//store numbers and display a dialog letting the user select which.
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String numberType = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
Map<String, String> NamePhoneType = new HashMap<String, String>();
NamePhoneType.put("Name", contactName);
NamePhoneType.put("Phone", phoneNumber);
if(numberType.equals("0"))
{
NamePhoneType.put("Type", "Work");
}
else if(numberType.equals("1"))
{
NamePhoneType.put("Type", "Home");
}
else if(numberType.equals("2"))
{
NamePhoneType.put("Type", "Mobile");
}
else
{
NamePhoneType.put("Type", "Other");
}
//Then add this map to the list.
mPeopleList.add(NamePhoneType);
}
phones.close();
}
}
people.close();
startManagingCursor(people);
}
并在PostExecute上将其设置为适配器
mAdapter = new SimpleAdapter(this, mPeopleList, R.layout.custcontview ,new String[] { "Name", "Phone" , "Type" }, new int[] { R.id.ccontName, R.id.ccontNo, R.id.ccontType });
mTxtPhoneNo.setAdapter(mAdapter);
我正在调用MyBackgroundTask()onCreate()。
第二项活动加载非常缓慢。不知道为什么有这么慢的负载。
请帮助我如何更快地加载活动。
谢谢!
答案 0 :(得分:0)
相比之下,磁盘操作总是“慢”。你真的不应该在主线程上进行数据库查询。学习使用Loaders代替;不再需要进行直接查询并使用startManagingCursor
(它已被弃用)。您可以使用CursorAdapter而不是迭代光标并关闭光标。
如果你仍然需要迭代光标,至少要这样做:
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
// etc
}