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.
答案 0 :(得分:0)
ItemModelList
是Model
个对象的列表。 LessonNameHolder
是String
。这意味着,无论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)){