应用程序崩溃时由于大数据而获取联系人列表

时间:2015-04-21 13:38:30

标签: android android-listview

我正在尝试获取联系人列表的所有电话号码和姓名。用少量的联系人列表分数很好但是app在获取大量联系人时崩溃了。 这是我的代码:

ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);

int position=0;
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) {
            Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
                    new String[]{id}, null);
            String phone=null;
            while (pCur.moveToNext()) {
                phone = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            }

            SearchGetterSetter searchContactList=new SearchGetterSetter();
            searchContactList.setPosition(position);
            searchContactList.setFist_name(name);
            searchContactList.setContactNo(phone);
            searchContactList.setChecked(false);
            contactList.add(searchContactList);
            originalList.add(searchContactList);
            position++;
        }
    }
    cur.close();
}

有没有办法批量获取联系人列表?

1 个答案:

答案 0 :(得分:0)

像这样的大型处理不应该在UI Thread..do里面完成 一个Java的线程。或者更好的选择是在Android API中使用AsyncTask。

private class myAsyncTask extends AsyncTask<(inputParams),(returnTypeForProgressUpdate), (retunType)> {
 protected Long doInBackground(inputParams... inputparam) {
     int input = inputparam[0];
     // Your Code In Here
     return modifiedInput;
 }

 protected void onProgressUpdate(Integer... progress) {
            // for update bar 
     setProgressPercent(progress[0]);
 }

 protected void onPostExecute(Long result) {
  //this is in the ui thread so use the result   
  showDialog("Loaded");
 }

要获得更好的信息,请访问.. http://developer.android.com/reference/android/os/AsyncTask.html#doInBackground(Params...)