Just want to check if data already exist(s) or not in ArrayList, but everytime getting : Not Exist(s) whereas data exists in ArrayList, and as a result i am getting duplicate records in a list..
DataArrayList.secondArraylist.add(new Second(actorList.get(position).getName(), actorList.get(position).getImage()));
System.out.println(DataArrayList.secondArraylist.size());
String strName = actorList.get(position).getName().toString();
Log.d("name:", strName);
for(int i=0; i<DataArrayList.secondArraylist.size(); i++)
{
if(DataArrayList.secondArraylist.get(i).getName().equals(strName)) {
System.out.println(DataArrayList.secondArraylist.get(i).getName());
Toast.makeText(context, "Exist(s)", Toast.LENGTH_SHORT);
}
else {
Toast.makeText(context, "Not Exist(s)", Toast.LENGTH_SHORT);
}
}
Problem:
Not getting any Toast message, which i am using to indicate that "Data Exists" or "Not"
Finally:
I would like to add item to arraylist if already not exist(s), else want to show Toast that item already exist(s)
You are comparing your list object DataArrayList.secondArraylist
with a String
if (DataArrayList.secondArraylist.equals(strName)) {
That will always return false
. Instead, create a method that loops through the list and checks the strName
against the name of the Second
objects that are stored in the list.
boolean contains(ArrayList<Second> list, String name) {
for (Second item : list) {
if (item.getName().equals(name)) {
return true;
}
}
return false;
}
Then use it
if (contains(DataArrayList.secondArraylist, strName)) {
System.out.println("Data Exist(s)");
} else {
System.out.println("Not Exist(s)");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With