Question

I am using the bellow code to list a unique list of people that sent me SMS. It works fine but still its a bit slow it takes 4 to 5 seconds to load and I have 650 SMS on my device any suggestion ?

 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       listSMS();
    }

private void listSMS()
{
    TextView tview = (TextView) findViewById(R.id.list);
    Uri uriSMSURI = Uri.parse("content://sms/inbox");
    ContentResolver cr= this.getContentResolver();
    Cursor cur = cr.query(uriSMSURI, null, null, null, null);
    LinkedHashSet contactList= new LinkedHashSet();
    String sms = "";
    while (cur.moveToNext()) {
        if(!contactList.contains(cur.getString(2)))
        {
            contactList.add(cur.getString(2));
            sms += "From :" + getContactName(cur.getString(2),cr)+"\n";
        }
    }
    cur.close();
    tview.append(sms);

}

public static String getContactName(String num, ContentResolver cr) {
        Uri u = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,Uri.encode(num));
        String[] projection = new String[] { ContactsContract.Contacts.DISPLAY_NAME};

        Cursor c = cr.query(u, projection, null, null, null);

        try {
            if (!c.moveToFirst())
                return num;

            int index = c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
            return c.getString(index);

        } finally {
            if (c != null)
                c.close();
        }
    }
Était-ce utile?

La solution

Instead of preparing the list of contacts with their names up front and then passing it to the adapter, try preparing the list with ids only and then fetch the corresponding names inside the adapter. This will solve the delay to start but will make scrolling of the ListView a bit slower which can be solved by using a View Holder or some caching mechanism to prevent fetching the same name more than once. Also note that the adapter will query for names of contacts that are currently visible to the user only.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top