0

I displayed the contacts in list view but when displaying it shows repeated phone numbers and names. so I tried to remove the duplicate names and numbers. It shows the single names but it displays the incorrect phone numbers of the user. How to solve that issue. This is my code :

public class Split extends AppCompatActivity implements AdapterView.OnItemClickListener {
    public  static  String TAG = "amount";
    ListView mainListView;
    ProgressDialog pd;
    public static final int PERMISSIONS_REQUEST_READ_CONTACTS = 100;
    final static List<String> name1 = new ArrayList<>();
    List<String> phno1 = new ArrayList<>();
    List<Long> bal = new ArrayList<>();
    List<Bitmap> img = new ArrayList<>();
    private Splitadapter mCustomAdapter;
    List<String> names = new ArrayList<String>();
    List<String> phonenumbers = new ArrayList<String>();
    private ArrayList<ContactModel> _Contacts = new ArrayList<ContactModel>();
    Button select;
    int amount=100;
    float result;
    String ph;
    String phoneNumber;
    EditText search;
    private FirebaseAuth mAuth;
    FirebaseUser firebaseUser;

    FirebaseFirestore db = FirebaseFirestore.getInstance();

    @SuppressLint("StaticFieldLeak")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setTitle("Split");
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }

        super.onCreate(savedInstanceState);
        setContentView(R.layout.split);
        mAuth = FirebaseAuth.getInstance();
        search = findViewById(R.id.search_bar);
        firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
        final List<String> phonenumber = new ArrayList<>();
        System.out.print(phonenumber);

        mainListView = findViewById(R.id.listview);
        showContacts();
        select = findViewById(R.id.button1);


        search.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
                // When user chan ged the Text


                mCustomAdapter.getFilter().filter(cs.toString());


//

            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                          int arg3) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable arg0) {
                // TODO Auto-generated method stub


                //ma.filter(text);
            }
        });
        select.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                StringBuilder checkedcontacts = new StringBuilder();
                ArrayList checkedcontacts1 = new ArrayList();
                ArrayList names = new ArrayList();
                System.out.println(".............." + (mCustomAdapter.mCheckStates.size()));
                System.out.println("name size is" + name1.size());
                int a = mCustomAdapter.mCheckStates.size();
                result = ((float) amount / a);
                System.out.println("final1 amount is " + result);
                long result1 = (long) result;
                System.out.println("final amount is " + result1);

                for (int k = 0; k <= a; k++) {

                    bal.add(result1);
                }
                System.out.println("balance" + bal);
                System.out.println("selected contacts split amount" + result);

                for (int i = 0; i < name1.size(); i++) // it displays selected contacts with amount

                {
                    if (mCustomAdapter.mCheckStates.get(i)) {
                        checkedcontacts.append(phno1.get(i)).append("\t").append("\t").append("\t").append(result1);
                        checkedcontacts1.add((phno1.get(i)));

                        names.add((name1.get(i)));
                        checkedcontacts.append("\n");
                        System.out.println("checked contacts:" + "\t" + phno1.get(i) + "\t" + "amount" + "\t" + result1);

                    }


                }


                System.out.println("checked names" + names);
                System.out.println(
                        "checkec contcts foggfgfgfgfgf" + checkedcontacts1
                );

                List<Object> list = new ArrayList<>();

                for (Object i : checkedcontacts1) {
                    list.add(i);
                }

                System.out.println("checked contacts size is" + checkedcontacts1.size());
                HashMap<String, HashMap<String, Object>> Invites = new HashMap<>();

                for (int i = 0; i < checkedcontacts1.size(); i++) {
                    HashMap<String, Object> entry = new HashMap<>();
                    entry.put("PhoneNumber", list.get(i));
                    entry.put("Name", names.get(i));

                    System.out.println("entry is" + entry);
                    for (int j = i; j <= i; j++) {
                        System.out.println("phonenumber" + i + ":" + list.get(i));
                        System.out.println("amount" + j + ":" + bal.get(j));
                        //dataToSave.put("phonenumber" +i, list.get(i));
                        entry.put("Amount", bal.get(j));

                    }
                    Invites.put("Invite" + i, entry);

                }


    }

    private void showContacts() // it is for to check the build versions of android . if build version is >23 or above it is set the permissions at the run time . if the build version is less than 23 the we give the permissions at manifest file .
    {if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
        requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, PERMISSIONS_REQUEST_READ_CONTACTS);
    }
    else {

        mCustomAdapter   = new Splitadapter(Split.this,_Contacts);
        //ArrayAdapter<String>   arrayAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1,aa);
        mainListView.setAdapter(mCustomAdapter);
        mainListView.setOnItemClickListener(this);
        mainListView.setItemsCanFocus(false);
        mainListView.setTextFilterEnabled(true);
        getAllContacts(this.getContentResolver());

    }

    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, // it is display the request access permission dilogue box to access the contacts of user.
                                           @NonNull int[] grantResults) {
        if (requestCode == PERMISSIONS_REQUEST_READ_CONTACTS) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission is granted
                showContacts();
            } else {
                Toast.makeText(this, "Until you grant the permission, we canot display the names", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void getAllContacts(ContentResolver getcontentResolver) {
        // it displays the contact phonenumber and name rom the phone book. and add to the list.

        Cursor phones = getcontentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");



        while (phones.moveToNext()) {
                String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME ));
                phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER ));

                long contactId = Long.parseLong(phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID)));

           if(!phonenumbers.contains(phoneNumber)) {
              phonenumbers.add(phoneNumber);
           }
            if(!names.contains(name)) {
                names.add(name);
            }



        }
        Collections.sort(names);



        for (int i = 0; i < names.size(); i++) {
            ContactModel contacts = new ContactModel();
            contacts.setName(names.get(i));
            contacts.setPhonenum(phonenumbers.get(i));

            _Contacts.add(contacts);
        }
        System.out.println("phonenumber size is" + phonenumbers.size());
        System.out.println("name size is" + names.size());
        phones.close();
    }



}

And this is my adapter class :

public class  Splitadapter extends BaseAdapter implements Filterable,CompoundButton.OnCheckedChangeListener

{
    public SparseBooleanArray mCheckStates;
    private ArrayList<ContactModel> _Contacts;
    private Context mContext;
    private LayoutInflater inflater;
    private ValueFilter valueFilter;
    private ArrayList<ContactModel> mStringFilterList;
    List<Bitmap> img = new ArrayList<>();

    public Splitadapter(Context context, ArrayList<ContactModel> _Contacts) {
        super();
        mContext = context;
        this._Contacts = _Contacts;
        mStringFilterList = _Contacts;
        mCheckStates = new SparseBooleanArray(_Contacts.size());
        this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        getFilter();

    }//End of CustomAdapter constructor


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

    @Override
    public Object getItem(int position) {
        return _Contacts.get(position).getName();
    }

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

    public class ViewHolder {
        TextView textviewName;
        TextView textviewNumber;
        CheckBox checkbox;
        ImageView image;
        int id;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        final int pos = position;
//
        if (convertView == null) {
            holder = new ViewHolder();

            convertView = LayoutInflater.from(mContext).inflate(R.layout.row, null);
            holder.textviewName = (TextView) convertView.findViewById(R.id.name);
            holder.textviewNumber = (TextView) convertView.findViewById(R.id.mobile);
            holder.checkbox = (CheckBox) convertView.findViewById(R.id.check);
            holder.image = convertView.findViewById(R.id.image);
            convertView.setTag(holder);
        }//End of if condition
        else {
            holder = (ViewHolder) convertView.getTag();
        }//End of else

        holder.checkbox.setId(position);
        holder.textviewName.setId(position);
        holder.textviewNumber.setId(position);


        holder.textviewName.setText(_Contacts.get(position).getName());
        holder.textviewNumber.setText(_Contacts.get(position).getPhonenum());
        holder.checkbox.setTag(position);
        holder.checkbox.setChecked(mCheckStates.get(position, false));
        holder.checkbox.setOnCheckedChangeListener(this);


            holder.image.setImageBitmap(_Contacts.get(position).getImage());



        //holder.id = position;

        return convertView;
//        }//End of getView method

    }

    boolean isChecked(int position) {// it returns the checked contacts
        return mCheckStates.get(position, false);
    }

    void setChecked(int position, boolean isChecked) { //set checkbox postions if it sis checked
        mCheckStates.put(position, isChecked);
        System.out.println("hello...........");
        notifyDataSetChanged();
    }

    void toggle(int position) {
        setChecked(position, !isChecked(position));
    }


    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            mCheckStates.put((Integer) buttonView.getTag(), true);
        } else {
            mCheckStates.delete((Integer) buttonView.getTag());
        }

    }

    @Override
    public Filter getFilter() {
        if (valueFilter == null) {

            valueFilter = new ValueFilter();

        }

        return valueFilter;
    }

    private class ValueFilter extends Filter {

        //Invoked in a worker thread to filter the data according to the constraint.
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            FilterResults results = new FilterResults();
            if (constraint != null && constraint.length() > 0) {
                ArrayList<ContactModel> filterList = new ArrayList<ContactModel>();
                for (int i = 0; i < mStringFilterList.size(); i++) {
                    if ((mStringFilterList.get(i).getName().toUpperCase())
                            .contains(constraint.toString().toUpperCase())) {
                        ContactModel contacts = new ContactModel();
                        contacts.setName(mStringFilterList.get(i).getName());
                        contacts.setPhonenum(mStringFilterList.get(i).getPhonenum());
                        filterList.add(contacts);
                    }
                }
                results.count = filterList.size();
                results.values = filterList;
            } else {
                results.count = mStringFilterList.size();
                results.values = mStringFilterList;
            }
            return results;
        }


        //Invoked in the UI thread to publish the filtering results in the user interface.
        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint,
                                      FilterResults results) {
            _Contacts = (ArrayList<ContactModel>) results.values;
            notifyDataSetChanged();
        }
    }
}    //End of CustomAdapter instance inne

And this my class :

public class ContactModel {
    String phonenum;
    String cname;
    Bitmap b;

    public String getPhonenum() {
        return phonenum;
    }
    public void setPhonenum(String phonenum) {
        this.phonenum = phonenum;
        System.out.println("se ph num"+phonenum);
    }
    public String getName() {
        return cname;
    }
    public void setName(String name) {
        this.cname = name;
    }
    public void setImage(Bitmap image) {
        this.b = image;
    }
    public Bitmap  getImage() {
        return b;
    }
}

How to solve that issue?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
vijju
  • 462
  • 9
  • 30

3 Answers3

0

Several wrong things here:

  • You have independent conditions for uniqueness of names vs phone numbers. It should be one to keep it all consistent.
  • Even if, somehow, the matching is preserved from the first point, you will mess everything up by sorting only the names list. The names will be ordered alphabetically but the phones will remain as they were.
NiVeR
  • 9,644
  • 4
  • 30
  • 35
0

You can use HashSet instead of arrayList and you must override equal and hashset method of your ContactModel class like this :

@Override
public boolean equals(Object o) {
    if(o == null) 
    return false;
    if (o == this) {
       return true;
    }

    if(o instanceof ContactModel) {
    return this.phoneNum.equals(o.phoneNum); //Or check other Parameters
    }
}

@Override
public int hashCode() {
    return this.phoneNum!= null ? this.phoneNum.hashCode() : 0;
}

if you do this , it will not add duplicate automatically contact in your list.

  • In that PhoneNum is the declared variable in that class? Which Array list is changed to Hash set?I am getting error at o.phonenum(that is phonenum is not defined) – vijju Oct 09 '18 at 09:06
  • @vijju it depends on your needs, you can check phonenum and cname together, that means if you have two object of contact and if phonenum and cname of these objects are eqaul so the both objects are equal and will not add to hashset , you can read this link for working with equal and hashcode : https://dzone.com/articles/working-with-hashcode-and-equals-in-java – Shayan Tabatabaee Oct 09 '18 at 09:12
  • @vijju : ArrayList that have uses ContactModel should replace to HashSet. and for that error you should cast o to ContacModel like this : ((ContactModel)o).getPhoneNum – Shayan Tabatabaee Oct 09 '18 at 09:16
-1

Use below link.I hope this will solve your problem.

Android get phone contacts and remove duplicates

ContentResolver cr = getContentResolver();
    Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.Contacts.DISPLAY_NAME + " ASC ");
    String lastnumber = "0";

    if (cur.getCount() > 0)
    {
        while (cur.moveToNext())
        {
            String number = null;
            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);
                while (pCur.moveToNext())
                {
                    number = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    Log.e("lastnumber ", lastnumber);
                    Log.e("number", number);

                    if (number.equals(lastnumber))
                    {

                    }
                    else
                    {
                        lastnumber = number;

                        Log.e("lastnumber ", lastnumber);
                        int type = pCur.getInt(pCur.getColumnIndex(Phone.TYPE));
                        switch (type)
                        {
                            case Phone.TYPE_HOME:
                                Log.e("Not Inserted", "Not inserted");
                                break;
                            case Phone.TYPE_MOBILE:

                                databaseHandler.insertContact(id, name, lastnumber, 0);
                                break;
                            case Phone.TYPE_WORK:
                                Log.e("Not Inserted", "Not inserted");
                                break;
                        }

                    }

                }
                pCur.close();
            }

        }
    }
Adam
  • 444
  • 5
  • 18