Check if list contains a text

时间:2018-02-01 18:27:07

标签: android listview

I have a list and a custom adapter:

ItemModelList = new ArrayList<Model>();
customAdapter = new CustomAdapter(getApplicationContext(), ItemModelList);
listView.setEmptyView(findViewById(R.id.empty));
listView.setAdapter(customAdapter);

I also have an EditText where I add items to list, and an imageView as button to add:

 addLesson = (EditText) findViewById(R.id.addLesson);
 AddLesson = (ImageView) findViewById(R.id.imgViewAdd);

When i press the add button, i want to check if the text inside the editext already exists in the listview. If exists i want to show a message, otherwise i want to add it in the list with a method(LessonRegistration).

AddLesson.setOnClickListener(new View.OnClickListener( ) {
        @Override
        public void onClick(View view) {

            // Checking whether EditText is Empty or Not
            CheckEditTextIsEmptyOrNot();

            if(CheckEditText){


                // If EditText is not empty then this block will execute.
                if (ItemModelList.contains(LessonNameHolder)){
                    Toast.makeText(MainMenu.this, "Already exists", Toast.LENGTH_LONG).show();
                    }
                else {
                    LessonRegistration(LessonNameHolder, CodeItem);
                    }


            }
            else {

                // If EditText is empty then this block will execute .
                Toast.makeText(MainMenu.this, "Add Lesson", Toast.LENGTH_LONG).show();

            }

        }
    });

LessonNameHolder has the String value of text from the editext. My problem is that the button adds items to the listView even if they are already there. I think the problem is here: if (ItemModelList.contains(LessonNameHolder))...

Maybe something with the objects in the ItemModelList.

Can you help me?

Thank you in advance.

1 个答案:

答案 0 :(得分:0)

ItemModelListModel个对象的列表。 LessonNameHolderString。这意味着,无论ItemModelList中的哪些项目,contains()来电都将始终返回false(因为String不是Model)。

您必须编写自己的“包含”方法,以自定义方式进行检查。假设每个Model实例都有一个名为lessonName的字段。然后你可以这样写:

public static boolean contains(List<Model> list, String lessonName) {
    for (Model model : list) {
        if (model.getLessonName().equals(lessonName)) {
            return true;
        }
    }
    return false;
}

现在你可以替换这一行:

if (ItemModelList.contains(LessonNameHolder)){

用这个:

if (contains(ItemModelList, LessonNameHolder)){