代码之家  ›  专栏  ›  技术社区  ›  Enamul Haque

在android中,从联系人获取数据花费了太多时间

  •  0
  • Enamul Haque  · 技术社区  · 5 年前

    我正在使用android设备联系人。如果android设备的联系人超过 ,从联系人获取数据 黑屏时间太长 . 我用下面的代码来获取数据

    private void fetchContacts1() {
        String order = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC";
        Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, order);
        while (cursor.moveToNext()) {
            String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            String phonenumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
    
        }
     cursor.close();
    }
    

    超过一万个联系人 . 你能建议我怎么处理吗。

    1 回复  |  直到 5 年前
        1
  •  2
  •   Arunachalam k    5 年前

    使用异步任务在后台加载联系人。首次加载后,将联系人列表存储到本地数据库中

    https://developer.android.com/guide/components/loaders

    https://stackoverflow.com/a/40017905/10239870

      class ContactLoader extends AsyncTask<Void, Void, List<Contact>> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            //visible your progress bar here
        }
    
        @Override
        protected List<Contact> doInBackground(Void... voids) {
            List<Contact> contacts = new ArrayList<>();
            String order = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC";
            Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, order);
            while (cursor.moveToNext()) {
                String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                String phonenumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                contacts.add(new Contact(name, phonenumber));
            }
            cursor.close();
            return contacts;
        }
    
        @Override
        protected void onPostExecute(List<Contact> contactList) {
            super.onPostExecute(contactList);
            //set list to your adapter
        }
    }
    
    
      class Contact {
        String name;
        String number;
    
        public Contact(String name, String number) {
            this.name = name;
            this.number = number;
        }
    
        public String getName() {
            return name;
        }
    
        public String getNumber() {
            return number;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public void setNumber(String number) {
            this.number = number;
        }
    }