如何阻止我的联系人列出两次?

时间:2016-04-01 11:52:15

标签: android android-contacts

我有一个示例应用程序,其中列出了我的Android手机中的联系人,我可以搜索它们。但是,通常会将联系人列出两次。我只希望它们被列出一次。我应该在代码中更改什么来解决这个问题?我在下面发布了我的代码的相关部分。

我在这里尝试how to remove duplicate contacts from arraylist,但我无法根据自己的需要修改代码。

MainActivity.java

package com.example.chris.contactlistcustomlistview;

        import android.app.Activity;
        import android.content.ContentResolver;
        import android.database.Cursor;
        import android.graphics.Bitmap;
        import android.net.Uri;
        import android.os.AsyncTask;
        import android.os.Bundle;
        import android.provider.ContactsContract;
        import android.provider.MediaStore;
        import android.util.Log;
        import android.view.View;
        import android.widget.AdapterView;
        import android.widget.ListView;
        import android.widget.SearchView;
        import android.widget.Toast;

        import java.io.IOException;
        import java.util.ArrayList;
        import java.util.List;


public class MainActivity extends Activity {

    // ArrayList
    ArrayList<SelectUser> selectUsers;
    List<SelectUser> temp;
    // Contact List
    ListView listView;

    // Cursor to load contacts list
    Cursor phones, email;

    // Pop up
    ContentResolver resolver;
    SearchView search;
    SelectUserAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        selectUsers = new ArrayList<SelectUser>();
        resolver = this.getContentResolver();
        listView = (ListView) findViewById(R.id.contacts_list);

        phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
//        retrieves contact information
        LoadContact loadContact = new LoadContact();
        loadContact.execute();

//        let's set up our search box,
        search = (SearchView) findViewById(R.id.searchView);

        //*** setOnQueryTextListener ***
        search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

            @Override
            public boolean onQueryTextSubmit(String query) {
                // TODO Auto-generated method stub

                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                // when the text in searchView changes, call the filter function
                adapter.filter(newText);
                return false;
            }
        });
    }

    // Load data on background
    class LoadContact extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

        @Override
        protected Void doInBackground(Void... voids) {
            // Get Contact list from Phone


            if (phones != null) {
                Log.e("count", "" + phones.getCount());
                if (phones.getCount() == 0) {
                    Toast.makeText(MainActivity.this, "No contacts in your contact list.", Toast.LENGTH_LONG).show();
                }

                while (phones.moveToNext()) {
                    Bitmap bit_thumb = null;
                    String id = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
                    String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                    String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    String EmailAddr = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA2));
                    String image_thumb = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_THUMBNAIL_URI));
                    try {
                        if (image_thumb != null) {
                            bit_thumb = MediaStore.Images.Media.getBitmap(resolver, Uri.parse(image_thumb));
                        } else {
                            Log.e("No Image Thumb", "--------------");
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
//what's happening here? For every user in the phonebook, show an image, the name, number, an id and maybe a checkbox?
                    SelectUser selectUser = new SelectUser();
                    selectUser.setThumb(bit_thumb);
                    selectUser.setName(name);
                    selectUser.setPhone(phoneNumber);
                    selectUser.setEmail(id);
                    selectUser.setCheckedBox(false);
                    selectUsers.add(selectUser);
                }
            } else {
                Log.e("Cursor close 1", "----------------");
            }
            //phones.close();
            return null;
        }

        @Override
//        when DoInBackground is finished, when we have our phone number, name etc... display the results in our listview.
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            adapter = new SelectUserAdapter(selectUsers, MainActivity.this);
            listView.setAdapter(adapter);

            // Select item on listclick
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                    Log.e("search", "here---------------- listener");

                    SelectUser data = selectUsers.get(i);
                }
            });

            listView.setFastScrollEnabled(true);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        phones.close();
    }
}

SelectUserAdapter.java

package com.example.chris.contactlistcustomlistview;

        import android.annotation.TargetApi;
        import android.content.Context;
        import android.graphics.Bitmap;
        import android.graphics.BitmapFactory;
        import android.os.Build;
        import android.util.Log;
        import android.view.LayoutInflater;
        import android.view.View;
        import android.view.ViewGroup;
        import android.widget.BaseAdapter;
        import android.widget.CheckBox;
        import android.widget.ImageView;
        import android.widget.TextView;

        import java.util.ArrayList;
        import java.util.List;
        import java.util.Locale;

/**
 * Created by Chris on 25/03/2016.
 */

public class SelectUserAdapter extends BaseAdapter {

    public List<SelectUser> _data;
    private ArrayList<SelectUser> arraylist;
    Context _c;
    ViewHolder v;
//    RoundImage roundedImage;

    public SelectUserAdapter(List<SelectUser> selectUsers, Context context) {
        _data = selectUsers;
        _c = context;
        this.arraylist = new ArrayList<SelectUser>();
        this.arraylist.addAll(_data);
    }

    @Override
    public int getCount() {
        return _data.size();
    }

    @Override
    public Object getItem(int i) {
        return _data.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    public View getView(int i, View convertView, ViewGroup viewGroup) {
        View view = convertView;
        if (view == null) {
            LayoutInflater li = (LayoutInflater) _c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = li.inflate(R.layout.inflate_listview, null);
            Log.e("Inside", "here--------------------------- In view1");
        } else {
            view = convertView;
            Log.e("Inside", "here--------------------------- In view2");
        }

//        we are making a cell format in the ListView, which will contain info like
//        number, name... the layout for this, with name, no, pic etc...
//        is contained in inflate_listview.xml, which describes how each cell data
//        loads into the listview
        v = new ViewHolder();

//      So, for example, title is cast to the name id, in activity main,
//        phone is cast to the id called no etc
        v.title = (TextView) view.findViewById(R.id.name);
        v.check = (CheckBox) view.findViewById(R.id.check);
        v.phone = (TextView) view.findViewById(R.id.no);
//        v.imageView = (ImageView) view.findViewById(R.id.pic);

//        for each new cell with title, name, number etc...
//
        final SelectUser data = (SelectUser) _data.get(i);
        v.title.setText(data.getName());
        v.check.setChecked(data.getCheckedBox());
        v.phone.setText(data.getPhone());



        Log.e("Image Thumb", "--------------" + data.getThumb());

        view.setTag(data);
        return view;
    }

    // Filter Class
    public void filter(String charText) {
        charText = charText.toLowerCase(Locale.getDefault());
//        _data is our list of Users, or contacts
        _data.clear();
//        If there is nothing in the searchbox,
//        then show all the contacts
        if (charText.length() == 0) {
            _data.addAll(arraylist);
//            or else....
        } else {
            for (SelectUser wp : arraylist) {
//                If a contact's phone number matches the input thus far that the user
//                is filtering for, then include it in the listview.
                if (wp.getPhone().toLowerCase(Locale.getDefault())
                        .contains(charText)) {
                    _data.add(wp);
                }
            }
        }
        notifyDataSetChanged();
    }
    static class ViewHolder {
//        In each cell in the listview show a name and phone number
//        ImageView imageView;
        TextView title, phone;
        CheckBox check;
    }
}

2 个答案:

答案 0 :(得分:0)

试试这个,我不确定它会解决这个问题。

 if (selectUsers.indexOf(selectUser) == -1) {
     selectUsers.add(selectUser);
    }

答案 1 :(得分:0)

public class MainActivity extends Activity {


    Cursor cursor;
    ListView mainListView;
    ArrayList hashMapsArrayList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (cursor != null) {
            cursor.moveToFirst();}
        try {

            cursor = getApplicationContext().getContentResolver()
                    .query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
            int Idx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID);
            int nameIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);

            int phoneNumberIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
            int photoIdIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_THUMBNAIL_URI);
            cursor.moveToFirst();


            Set<String> ids = new HashSet<>();
            do {
                System.out.println("=====>in while");
                String contactid=cursor.getString(Idx);
                if (!ids.contains(contactid)) {
                    ids.add(contactid);
                    HashMap<String, String> hashMap = new HashMap<String, String>();
                   String  name = cursor.getString(nameIdx);
                    String phoneNumber = cursor.getString(phoneNumberIdx);
                    String image = cursor.getString(photoIdIdx);
                    System.out.println("Id--->"+contactid+"Name--->"+name);
                    System.out.println("Id--->"+contactid+"Number--->"+phoneNumber);

                    if (!phoneNumber.contains("*")) {
                        hashMap.put("contactid", "" + contactid);
                        hashMap.put("name", "" + name);
                        hashMap.put("phoneNumber", "" + phoneNumber);
                        hashMap.put("image", "" + image);
                        // hashMap.put("email", ""+email);
                        if (hashMapsArrayList != null) {
                            hashMapsArrayList.add(hashMap);}
//                    hashMapsArrayList.add(hashMap);
                    }
                }

            } while (cursor.moveToNext());


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
}
}