2014-02-11 59 views
0

嗨我正在開發一個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

也許你能解釋一下什麼是*載入速度很慢*。在加載數據之前它是否顯示黑屏?或者數據加載非常緩慢?無論如何,最好還包括與創建第二個活動相關的代碼(例如'onCreate()',...) –

+0

是的,它顯示了一段時間的黑屏。我打電話給MyBackgroundTask()onCreate()。 – sanjana

+0

如果它顯示黑屏,則佈局創建(Main/UI線程)被某些繁重的進程阻止。你的MyBackgroundTask是填充適配器還是不同的任務?如果可能的話,在第二個活動中發佈完整的代碼「onCreate()」。 –

回答

0

通過比較,磁盤操作總是「慢」。你真的不應該在主線程上進行數據庫查詢。學習改用Loaders;不再需要直接查詢並使用startManagingCursor(反正它已被棄用)。而不是迭代光標並關閉它,您可以改爲使用CursorAdapter

如果您仍然需要遍歷光標,至少要做到這樣說:

for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { 
    // etc 
}