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?