Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList check if data already exists

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)

like image 608
Oreo Avatar asked May 02 '15 12:05

Oreo


1 Answers

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)");
}
like image 167
pathfinderelite Avatar answered Oct 13 '22 22:10

pathfinderelite